问题描述
实际上,我的目标是将CSS:hover替换为JavaScript。 原因是我需要在可变数量的div上执行一个循环,该循环将嵌套在对div作出反应的父div内。
但是,问题在于,我不知道如何仅将悬停的div作为目标,而无需对特定ID进行硬编码-一旦将其应用于我的项目,即tumblr主题,我将无法做到。
HTML
<div id="motherbox">
<div class="middlebox">
<div class="childbox">One</div>
<div class="childbox">Two</div>
<div class="childbox">Three</div>
</div>
</div>
<div id="motherbox">
<div class="middlebox">
<div class="childbox">One</div>
<div class="childbox">Two</div>
<div class="childbox">Three</div>
<div class="childbox">Four</div>
<div class="childbox">Five</div>
</div>
</div>
CSS
#motherbox {
width:30%;
height:100px;
margin:100px auto;
background-color:gray;
}
JavaScript的
document.getElementById("motherbox").onmouseenter = function(){
this.style.backgroundColor = 'blue';
};
document.getElementById("motherbox").onmouseleave = function(){
this.style.backgroundColor = "gray";
};
我的问题是-如何使具有相同类或ID的div在悬停时使用javascript(而不是CSS)进行单独反应(或者不是一次全部响应)?
感谢您的时间。
1楼
Sachin Nambiar Nalavattanon
1
已采纳
2015-07-25 17:16:55
基本上,您可以使用getElementsByClassName选择具有特定类的元素。
这是一个工作 。
var elements = document.getElementsByClassName('childbox');
for(var i=0; i<elements.length; i++) {
elements[i].onmouseleave = function(){
this.style.backgroundColor = "blue";
};
}
2楼
Pawe? Smo?ka
0
2015-07-25 17:10:25
因此,请使用以下方法代替getElementById: :
并为您要在其上发生该事件的div提供类。