【发布时间】:2018-02-10 18:01:40
【问题描述】:
我正在制作一个物理引擎,它利用 JavaScript 创建具有物理属性的盒子,这些盒子以窗口大小的比例应用于它们。但是,函数document.getElementByClassName("box") 找不到包含这些盒子的所有物理属性的名为box 的类。
我正在尝试分配一个变量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);
}
底部的事件监听器给出错误,因为boxelem 未定义,因为getElementsByClassName 找不到元素。
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?) 和 (Change an element's class with JavaScript),但不确定如何将其应用于我的问题。
【问题讨论】:
-
我没有看到类
box的元素。所以document.getElementsByClassName("box")方法总是返回一个空数组。 -
document.getElementByClassName()是否可以引用在 JS 而不是 HTML 中实例化的类? @D.西蒙 -
document.getElementsByClassName("box")查找具有给定类的 HTML 元素。找不到 JavaScriptclasses,因为 JS 没有真正的类。 -
我现在明白了,虽然我如何在不创建 HTML 类的情况下引用 box 类的元素?
标签: javascript getelementsbyclassname