javascript - JQuery的mouseout函数超时问题

标签 javascript jquery

我在使用 JQuery mouseout 函数和 setTimeout 时遇到问题。

我想要实现的是,当我悬停一个元素时,它会改变背景。当我离开该元素(因此触发 mouseout)时,背景应在 1 秒后返回到原始状态。

如果我使用下面的代码,仅当我离开该元素时才会调用 goBack 函数:

.mouseover(function(){
    changeBackground();
})
.mouseout(function(){
    //setTimeout(function() {
    goBack();
    //}, 1000);
});

但是如果我取消注释超时函数(这就是我想要实现的),即使我不离开该元素,也会调用goBack函数。

有什么帮助或建议可以避免这个问题吗?

最佳答案

这是因为事件冒泡,所以使用 mouseentermouseleave而不是 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 from mouseover in the way it handles event bubbling. If mouseover 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. The mouseenter 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/

相关文章:

php - 使用 jQuery 加载搜索表单结果,而不是在新页面上

javascript - 当用户关闭浏览器窗口时发送ajax

javascript - 查找网页上唯一启用的按钮

javascript - 从弹出窗口登录网站后如何重定向到主窗口

javascript - Redux 在 Meteor.call 内调度或获取 Meteor.call 值

javascript - 在 jquery 中使用 Slide Down 显示隐藏的表单域

javascript - 是否可以更改 :before using javascript or jQuery

javascript 在 createTextNode 中用 <br> 替换\n

javascript - jQuery - 在文本区域中查找文本

javascript - CSS 相对背景在插入 html 代码时不会扩展