"Cannot read property 'style' of undefined" onmousemove

"Cannot read property 'style' of undefined" onmousemove

所以在我的网站上,我想要一些文本跟随我的光标。我使用以下 JS:

var balls = document.getElementsByClassName("text1");
  document.onmousemove = function(){
    var x = event.clientX * 100 / window.innerWidth + "%";
    var y = event.clientY * 100 / window.innerHeight + "%";

    for(var i=0;i<2;i++){
      balls[i].style.left = x;
      balls[i].style.top = y;
      balls[i].style.transform = "translate(-"+x+",-"+y+")";
    }
  };

但在 chrome 中,我收到以下错误消息:

Uncaught TypeError: Cannot read property 'style' of undefined at HTMLDocument.document.onmousemove (script.js:7) document.onmousemove @ script.js:7

谁能帮帮我?

您的代码中的问题是您一直循环到“i==2”,但您可能已将“text1”class 附加到仅 1 个元素,这就是循环达到 balls[1 的原因] 然后它抛出错误“无法读取未定义的属性 'style'”。

因此,要么减小循环最大值,要么将“text1”class附加到更多元素。

这是工作示例。

<!DOCTYPE html>
<html>
<script>
  var balls = document.getElementsByClassName("text1");
  document.onmousemove = function() {
    var x = event.clientX * 100 / window.innerWidth + "%";
    var y = event.clientY * 100 / window.innerHeight + "%";
    for (var i = 0; i < 2; i++) {
      balls[i].style.left = x;
      balls[i].style.top = y;
      balls[i].style.transform = "translate(-" + x + ",-" + y + ")";
    }
  };
</script>

<body>
  <p class="text1">Hello</p>
  <p class="text1">World</p>
</body>

</html>