2015-10-20 32 views
2

我有一堆位於圖像頂部的div。 我想讓div隱藏的分數出現在鼠標懸停上。爲了達到這個目的,我嘗試將div的zIndex設置爲低於圖像的zIndex值,以便顯示出來。但我似乎可以選擇所有的div。爲什麼我不能在這裏更改zIndex?

這裏是我的javascript代碼:

window.onload = function() { 
    var block = document.getElementById('container'); 

    block.addEventListener('mouseover', function() { 
     var blocks = document.querySelectorAll("#container div"); 
     var index = 0, length = blocks.length; 
     for (var index = 0; index < length; index++) { 
      blocks[index].style.zIndex = 2; 
     } 
    }); 

    for (var i = 0; i < 40; i++) { 
     for (var j = 0; j < 40; j++) { 
      var div = document.createElement("div"); 
      div.className = "block"; 
      div.style.left = j * 25 + 'px'; 
      div.style.top = i * 25 + 'px'; 
      div.style.display = "inline-block"; 
      div.style.verticalAlign = "top"; 
      div.style.zIndex = "1"; 
      document.getElementById("container").appendChild(div); 
     } 
     var jump = document.createElement("br"); 
     document.getElementById("container").appendChild(jump); 
    } 
}; 

我有什麼錯?謝謝。 div容器具有放置在創建的內部div之下的背景圖像。

+0

可能是因爲'Array'沒有屬性'style'。 – BenM

+0

另外請記住,這些元素需要被絕對定位,以便'z-index'完全可以工作(呵呵 - 感謝@ j08691指出了這一點 - 儘管保留我原來的評論) – eithed

+1

'mousehover' event does not存在。 'mouseover'是正確的。 – Sebas

回答

1

document.querySelectorAll返回一組元素。你需要逐個循環。

var blocks = document.querySelectorAll("#container div"); 
var index = 0, length = blocks.length; 
for (; index < length; index++) { 
    blocks[index].style.zIndex = 1; 
} 

如果你只是在尋找返回的第一個元素一個元素,你也可以用它document.querySelector發現,選擇相匹配,您可以爲您最初在你的代碼對直接工作。

+0

我會現在測試它,謝謝你的提示 – abedzantout

+0

我在我的問題中添加了進一步的解釋。謝謝您的幫助 – abedzantout

相關問題