我試圖使div
移動和反彈一旦到達容器的邊緣div
我使用此代碼這樣做,但調試器顯示的這個錯誤Cannot read property 'offsetWidth' of undefined
當達到容器的邊緣時,使移動和反彈
var speed = 10,
direction = 1;
var ballElement = document.getElementsByClassName('ball'),
containerElement = document.getElementsByClassName('mainDiv');
if (ballElement) {
var boxLeftPos = ballElement.offsetLeft,
boxRightPos = boxLeftPos + ballElement.offsetWidth;
if (boxRightPos > document.containerElement.offsetWidth) {
direction = -1;
}
if (boxLeftPos < 0) {
direction = 1;
}
ballElement.style.left = (boxLeftPos + speed * direction) + 'px';
}
誤差在這一行:
if (boxRightPos > document.containerElement.offsetWidth)