javascript 怎样实现 hover 事件延时触发 jquery 的 toggleClass()

如题,我希望移动到 .dropdown 区域内时,.item 能够延时个1秒再添加 .highlight,离开时也延时1秒再移除 highlight,改怎么实现呢?

<div class="dropdown">
  <div class="item">helloworld</div>
</div>
.item {
    background: pink;
}
.highlight {
  height: 100px;
  background: yellow;
}
$('.dropdown').hover(function() {
    $('.item', this).toggleClass('highlight');
});

http://jsfiddle.net/AKcHr/

阅读 9.5k
2 个回答
$('.dropdown').hover(function() {
    var $item = $('.item', this);
    setTimeout(function(){$item.toggleClass('highlight');}, 1000);
});

变量在setTimeout() 和 setInterval()没有用,所以用function代替.

需要记住离开或者进入定时器定时器ID, 进入或者离开时, 需要清除上一次定时器任务. 再创建新的定时

var tid;
$('.dropdown').hover(
  function(){
    if (tid) { clearTimeout(tid); }
    tid = setTimeout(function(){
      tid = 0;
      $('.dropdown').addClass('highlight');
    }, 1e3);
  },
  function(){
    if (tid) { clearTimeout(tid); }
    tid = setTimeout(function(){
      tid = 0;
      $('.dropdown').removeClass('highlight');
    }, 1e3)
  }
);
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题