我正在製作一個物理引擎,利用JavaScript來創建具有應用於物理屬性的窗口大小的框。但是,函數document.getElementByClassName("box")
無法找到包含這些框的所有物理屬性的稱爲框的類。Javascript內部類未找到document.getElementByClassName
我想分配一個變量boxelem
來包含每個盒子的位置屬性,以便將鼠標操作集成到我的程序中。我已經嘗試通過代碼執行此操作:
var boxelem = document.getElementsByClassName("box");
然後將鼠標懸停在Boxelem的事件偵聽器上。
必要的代碼:因爲boxelem
不會由於不被getElementsByClassName
發現的元素定義
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);
}
底部的事件監聽器提供了一個錯誤。 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」)''方法總是返回一個空數組。 –
[QuerySelectorAll,getElementsByClassName和其他getElementsBy \ *方法返回什麼]的可能重複(https://stackoverflow.com/questions/10693845/what-do-queryselectorall-getelementsbyclassname-and-other-getelementsby-method) – Li357
'document.getElementByClassName()'引用在JS內而不是HTML中實例化的類? @ D.Simon –