2014-12-31 47 views
1

我試圖使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) 

LIVE DEMO

回答

2

getElementsByClassName返回一個數組。如果你有一個類只有一個元素,添加[0]找回它:getElementsByClassName('ball')[0]

if (boxRightPos > document.containerElement.offsetWidth) {

刪除document.工作演示:http://jsfiddle.net/7rw1t8eh/

1

document.containerElement未定義它應該只是containerElement的外觀

1

document.getElementsByClassName的結果是一個nodeList對象。所以它沒有offsetWidth或style。您可以改用document.querySelector('.ball'),或使用containerElement[0]