有一些带有子元素的元素,当你悬停时,应该在间隔后将子元素添加到类中。
我可以添加该类能够悬停,当我从父类中删除鼠标时首先删除,然后由于某种原因再次添加,我不明白发生了什么。
$('.field_icon')
.mouseover(function() {
$(this).children('.field-item').each(function(i, el) {
setTimeout(function() {
$(el).addClass('active');
}, 100 + (i * 300));
})
})
.mouseleave(function() {
$(this).children('.field-item').removeClass('active')
})
.field-item {
display: inline-block;
width: 50px;
height: 50px;
background: #7CB342;
}
.field-item.active {
background: #FF9800;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div class="field_icon">
<div class="field-item"></div>
<div class="field-item"></div>
<div class="field-item"></div>
<div class="field-item"></div>
</div>
<div class="field_icon">
<div class="field-item"></div>
<div class="field-item"></div>
<div class="field-item"></div>
<div class="field-item"></div>
</div>
<div class="field_icon">
<div class="field-item"></div>
<div class="field-item"></div>
</div>
<div class="field_icon">
<div class="field-item"></div>
<div class="field-item"></div>
<div class="field-item"></div>
</div>
答案 0 :(得分:3)
您需要使用mouseleave
事件中的clearTimeout
清除超时间隔;
//Declare an empty array to store the timeoutID
var t = [];
$('.field_icon')
.mouseover(function() {
$(this).children('.field-item').each(function(i, el) {
//store the reference in a variable
var t1 = setTimeout(function() {
$(el).addClass('active');
}, 100 + (i * 300));
//Push it the array
t.push(t1);
})
})
.mouseleave(function() {
//iterate and Clears the delay set setTimeout
t.forEach(clearTimeout);
//reset array to emepty
t.length = 0;
$(this).children('.field-item').removeClass('active')
})
&#13;
.field-item {
display: inline-block;
width: 50px;
height: 50px;
background: #7CB342;
}
.field-item.active {
background: #FF9800;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div class="field_icon">
<div class="field-item"></div>
<div class="field-item"></div>
<div class="field-item"></div>
<div class="field-item"></div>
</div>
<div class="field_icon">
<div class="field-item"></div>
<div class="field-item"></div>
<div class="field-item"></div>
<div class="field-item"></div>
</div>
<div class="field_icon">
<div class="field-item"></div>
<div class="field-item"></div>
</div>
<div class="field_icon">
<div class="field-item"></div>
<div class="field-item"></div>
<div class="field-item"></div>
</div>
&#13;
答案 1 :(得分:0)
使用mouseenter,而不是鼠标悬停:
http://www.w3schools.com/jquery/event_mouseover.asp
与mouseenter事件不同,如果鼠标指针进入任何子元素以及所选元素,则会触发mouseover事件。只有当鼠标指针进入所选元素时才会触发mouseenter事件。
因此,基本上,当您将鼠标移到子元素上时,它会在父元素获取子元素移动时再次重新添加所有事件。