无法正确处理:将事件侦听器添加到来自 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);
请告诉我下面的代码有什么问题:
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);