[英]Var doesn't get elements from document.getElementsByClassName()
[英]Can't Get It Right: Adding An Event Listener to Elements From getElementsByClassName
請告訴我以下代碼出了什么問題:
for(var i = 0; i < image.length; i++) {
image[i].appendChild(overlay);
image[i].addEventListener("mouseover", function() {
this.firstChild.style.backgroundColor = "rgba(0, 0, 0, 0)";
this.style.backgroundSize = "340px 240px";
this.style.WebkitTransition = "all 0.5s";
this.style.transition = "all 0.5s";
}, false);
image[i].addEventListener("mouseout",function() {
this.firstChild.style.backgroundColor = "rgba(0, 0, 0, 0.7)";
this.style.backgroundSize = "300px 200px";
this.style.WebkitTransition = "all 0.5s";
this.style.transition = "all 0.5s";
}, false);
}
這是通過使用getElementsByClassName()函數獲得的元素的圖像數組進行循環的。
var image = document.getElementsByClassName(ClassName);
我從瀏覽器控制台收到的錯誤是這樣的:
如果我錯過了您需要了解的任何信息,請告訴我。 或者,如果您對如何改進此代碼有任何建議,請繼續使用。
注意:沒有jQuery。
您只有一個overlay
元素,只是在更改它的父元素。 循環之后,它將添加到image
集合中的最后一個元素。
要解決此問題,您可以在每次將overlay
附加到新的父對象時創建一個副本,如下所示:
image[i].appendChild(overlay.cloneNode(true));
萬一克隆的元素有一個id
,您必須為每個克隆創建一個新的id
,如下所示:
var clone = overlay.cloneNode(true);
clone.id = clone.id + i; // Adds i to the end of the id, use date or some else unique string instead, if you're running the loop multiple times
image[i].appendChild(clone);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.