Javascript document.getElementByClassName 未找到内部 class

Javascript Internal class not found by document.getElementByClassName

我正在制作一个物理引擎,该引擎利用 JavaScript 来创建具有 window 大小比例的物理属性的框。但是,函数document.getElementByClassName("box")无法找到包含这些盒子所有物理属性的class调用盒子。

我正在尝试分配一个变量 boxelem 来包含每个单独框的位置属性,以便将来我可以将鼠标操作集成到我的程序中。我试过通过代码做到这一点:
var boxelem = document.getElementsByClassName("box"); 然后将鼠标悬停在事件侦听器上添加到 boxelem。

所需代码:

var canvas;
var ctx;
var box = [];
var boxelem;

//Startup Code
window.onload = function(e) {
    canvas = document.getElementById("c");
    ctx = canvas.getContext("2d");
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;
    box = [new box(10, 20, "cyan"), new box(299, 40, "red"), new box(90, 50,
      "black"), new box(29, 20, "turquoise")];
    boxelem = document.getElementsByClassName("box");
    noscroll();
    update();
  }

  //Physic Clock (For real-time physics)
var clock = {
    lasttick: 0,
    tick: function() {
      var td = performance.now() - this.lasttick;
      this.lasttick = performance.now();
      return td / 1000;
    },
    reset: function() {

    }
  }

  //Box objects be created here (Box Class)
var box = function(x, y, color) {
  var _this = this;
  //First Spawn Physics and Settings
  _this.x = Math.random() * (canvas.width - 50);
  _this.y = Math.random() * (canvas.height - 50);
  _this.vx = 0;
  _this.vy = Math.random() * 150;
  _this.ax = 0;
  _this.ay = 440;
  _this.color = color;

  _this.draw = function() {
      ctx.fillStyle = _this.color;
      ctx.fillRect(_this.x, _this.y, 50, 50);
    }

    //Normal Physics
  _this.update = function(t, mX, mY) {
    if (mX != 0) {
      _this.x += _this.vx * t;
      _this.vx += mX * t;
    } else {
      _this.x += _this.vx * t;
      _this.vx += _this.ax * t;
    }
    _this.y += _this.vy * t;
    _this.vy += _this.ay * t;

    //Boundary Creation
    if ((_this.y + 55) > canvas.height) {
      _this.vy -= _this.ay * t;
      _this.vy = 0;

    }
    if ((_this.x + 55) > canvas.width) {
      _this.vx -= _this.ax * t;
      _this.vx = 0;
    }
    if ((_this.y) < 0) {
      _this.vy -= _this.ay * t;
      _this.vy = 0;
      _this.y = (canvas.height + 20);
    }
    if ((_this.x) < 0) {
      _this.vx -= _this.ax * t;
      _this.vx = 0;
    }
  }
}

//Get mouse position if over a box
var pageX = 0;
var pageY = 0;
for (var z = 0; z < box.length; z++) {
  boxelem.addEventListener("mouse", mPos, false);
}

底部的事件监听器报错,因为getElementsByClassName没有找到元素导致boxelem没有定义。 HTML代码:

<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
     <script type=text/javascript src="Physics.js"></script>
     <meta charset="utf-8" />
     <title>Physics Engine of Boxes</title>
 </head>
 <body>
     <canvas id="c"></canvas>
</body>
</html>

我查看了 (Unobtrusive Javascript-Basic Implementation: How do I bind all elements of a particular class to a function in Javascript?) and (Change an element's class with JavaScript),但不确定如何将其应用到我的问题中。

你的这个循环体没有访问索引。此外,您使用的 .length 来自 box 函数而不是 boxelem 集合。

这个:

for (var z = 0; z < box.length; z++) 
{
  boxelem.addEventListener("mouse", mPos, false);
}

应该是这样的:

for (var z = 0; z < boxelem.length; z++) 
{
  boxelem[z].addEventListener("mouse", mPos, false);
}

正如 D Simon 在下面指出的那样,boxelemundefined,因为在 DOM 加载之前您不会填充该变量。您应该确保在尝试使用该变量之前获取这些项目。


如果将所有代码移至 window.onload,它应该可以工作。请注意,在加载所有资源之前,window.onload 不会 运行。您可能想要使用一个可以更快触发的不同事件,但那是另一个话题了。

//Startup Code
window.onload = function(e) {
    var canvas = document.getElementById("c");
    var ctx = canvas.getContext("2d");
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;
    var box = [new box(10, 20, "cyan"), new box(299, 40, "red"), new box(90, 50,
      "black"), new box(29, 20, "turquoise")];
    var boxelem = document.getElementsByClassName("box");
    noscroll();
    update();

    //Physic Clock (For real-time physics)
    var clock = {
        lasttick: 0,
        tick: function() {
          var td = performance.now() - this.lasttick;
          this.lasttick = performance.now();
          return td / 1000;
        },
        reset: function() {

        }
      }

    //Box objects be created here (Box Class)
    var box = function(x, y, color) {
      // ...implementation...
    }

    //Get mouse position if over a box
    var pageX = 0;
    var pageY = 0;
    for (var z = 0; z < boxelem.length; z++) {
      boxelem[z].addEventListener("mouse", mPos, false);
    }
}