我在使用 JQuery mouseout
函数和 setTimeout
时遇到问题。
我想要实现的是,当我悬停一个元素时,它会改变背景。当我离开该元素(因此触发 mouseout)时,背景应在 1 秒后返回到原始状态。
如果我使用下面的代码,仅当我离开该元素时才会调用 goBack
函数:
.mouseover(function(){
changeBackground();
})
.mouseout(function(){
//setTimeout(function() {
goBack();
//}, 1000);
});
但是如果我取消注释超时函数(这就是我想要实现的),即使我不离开该元素,也会调用goBack
函数。
有什么帮助或建议可以避免这个问题吗?
最佳答案
这是因为事件冒泡,所以使用 mouseenter和 mouseleave而不是 mouseover 和 mouseout 或使用 hover就像,
.hover(function(){
changeBackground();
},function(){
setTimeout(function() {
goBack();
}, 1000);
});
或
.mouseenter(function(){
changeBackground();
})
.mouseleave(function(){
setTimeout(function() {
goBack();
}, 1000);
});
来自 jQuery.mouseenter
的文档,
The
mouseenter
event differs frommouseover
in the way it handles event bubbling. Ifmouseover
were used in this example, then when the mouse pointer moved over the Inner element, the handler would be triggered.This is usually undesirable behavior. Themouseenter
event, on the other hand, only triggers its handler when the mouse enters the element it is bound to, not a descendant. So in this example, the handler is triggered when the mouse enters the Outer element, but not the Inner element.
更新了,这里是超时问题,您需要在更改 mouseenter 上的背景之前清除超时
function changeBackground() {
$('#content').addClass('yellow');
}
function goBack() {
$('#content').removeClass('yellow');
}
var t=null;//clear timeout variable
$(function() {
$('#content').mouseenter(function() {
clearTimeout(t);// clear previous timeouts
changeBackground();
}).mouseleave(function() {
t=setTimeout(function() { //set new timeouts
goBack();
}, 1000);
});
});
#content {
background-color: #eee;
padding: 20px;
cursor: pointer;
}
.yellow {
background-color: #ffff00 !important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="content">
Lorem ipsum doner inut
</div>
关于javascript - JQuery的mouseout函数超时问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32309639/