仅尊重一系列 javascript/jQuery 事件中最新事件的最简单方法
我必须想象这是 javascript/jQuery 的常见用例,所以如果它在网站的其他地方,请原谅我,我搜索了它但找不到这个基本用例。
我有一个可见的 div (A)。将鼠标悬停在该 div 上会显示一些其他 div(B 和 C)。取消悬停任何这些 div(A、B 或 C)将隐藏显示的两个 div(B 和 C)。
很简单,对吧?问题在于,当您快速连续多次悬停和取消悬停时,这种简单的行为会导致丑陋,因为事件全部叠加,然后它就像手风琴一样工作一段时间。
我尝试将 typewatch 函数带入等式中:
var typewatch = (function(){
var timer = 0;
return function(callback, ms){
clearTimeout (timer);
timer = setTimeout(callback, ms);
}
})();
但我猜我无法正确使用它(也许我必须调用一个调用 typewatch 本身的自定义切换函数,或者其他什么?)。
为了便于理解,下面是具体案例的 jsfiddle: http://jsfiddle.net/tchalvakspam/KG3P9/7/
但总的来说,我可以观看多个活动并只关注最新的活动吗?
I have to imagine that this is a common use case for javascript/jQuery, so forgive me if it's somewhere else on the site, I searched for it and couldn't find this basic use case.
I have a visible div (A). Hovering that div displays some other divs (B & C). Unhovering any of those divs (A, B, or C) will hide the two shown divs (B & C).
Simple enough, right? The problem is that that simple behavior leads to ugliness when you hover and un-hover a number of times in quick succession, since the events all stack and then it just acts like an accordian for a while.
I tried bringing the typewatch function into the equation:
var typewatch = (function(){
var timer = 0;
return function(callback, ms){
clearTimeout (timer);
timer = setTimeout(callback, ms);
}
})();
But I wasn't able to use it correctly, I guess (perhaps I would have to call a single custom toggle function that calls typewatch itself, or something?).
For ease of understanding, here is a jsfiddle of the exact case:
http://jsfiddle.net/tchalvakspam/KG3P9/7/
But speaking in general, how can I catch multiple events and only honor the latest one?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我将 e.preventDefault() 与 jQuery 事件结合使用,以阻止事件在树上传播。
I use e.preventDefault() with jQuery events to stop the event from propagating up the tree.
这其实是曾经让我很困扰的事情。在制作动画之前,调用
$.stop()
这将冻结任何当前的内容动画在其轨道上,并接受你给它的新目标。这遵循 jQuery API 中为
$.stop()
方法本身,因为他们提供了一个类似的示例,使用单个图像。演示:http://jsbin.com/adeqef/2/edit
This is actually something that used to bother me a lot. Before you animate, call
$.stop()
which will freeze any present animation in its tracks, and pick up with the new goal you give it.This follows the documentation provided in the jQuery API for the
$.stop()
method itself as they present a similar example, using a single image.Demo: http://jsbin.com/adeqef/2/edit