如何使用DOM为CSS元素提供增量坐标?

问题描述 投票:1回答:1

我是JS和Web开发人员的新手。我遇到了这个问题:

[猫和老鼠在CSSHTML中完成。我要实现的目标是在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);
});
javascript dom setinterval
1个回答
0
投票

已修复并清理。问题是$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部分

© www.soinside.com 2019 - 2024. All rights reserved.