我是JS
和Web开发人员的新手。我遇到了这个问题:
[猫和老鼠在CSS
和HTML
中完成。我要实现的目标是在Y axis
上递增移动猫的位置,使其与鼠标位于同一水平线上,给人的印象是猫没有立即跳到鼠标上。
[最终,但是暂时,我希望猫从100 top
移至300 top
,然后从300 top
移至600 top
,这是鼠标在Y axis
上的坐标。这是我的js
文件,但似乎无法解决,猫去了300 top
并坐在那里,所以我想我应该和你们一起寻求帮助:-)。
您能帮助任何人吗? Thx
document.addEventListener("DOMContentLoaded", () => {
const $cat = document.querySelector("#cat");
setInterval(() => {
var currentPosition = $cat.style.top;
var newPosition;
var direction = 200;
if (currentPosition <= 100) {
direction = 200;
} else if (currentPosition <= 300) {
direction = 300;
}
newPosition = currentPosition + direction;
$cat.style.top = newPosition + "px";
}, 1000);
});
已修复并清理。问题是$cat.style.top
是一个字符串,您试图添加一个将它们串联在一起的字符串。然后导致无法识别的CSS属性,因此该项目被卡住。
document.addEventListener("DOMContentLoaded", () => {
const cat = document.querySelector("#cat");
const regEx = /\d+/ // matches all digits
let direction, currentPosition = 0;
setInterval(() => {
currentPosition = regEx.exec(cat.style.top)[0]
if (currentPosition <= 100) {
direction = 200;
} else if (currentPosition <= 300) {
direction = 300;
} else {
console.error(`skipped if statements oO`)
}
cat.style.top = (currentPosition + direction) + "px";
}, 1000);
});
对于所有担心regEx的人,都有一个String.substring()
函数,该函数也可以用于摆脱cat.style.top
末尾的px部分