javascript 在鼠标悬停时向 jquery 事件添加延迟

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3661635/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 01:51:51  来源:igfitidea点击:

Adding delay to jquery event on mouseover

javascriptjquerychildrenshow-hideonmouseover

提问by TLK

I am trying to add a simple delay to a mouseover event of a child and having difficulties. (Still learning!)

我正在尝试为孩子的鼠标悬停事件添加一个简单的延迟并且遇到困难。(仍在学习!)

This enables me to show the popup after a delay, but shows all of them simultaneously:

这使我能够在延迟后显示弹出窗口,但同时显示所有这些:

onmouseover='setTimeout(function() { $(\".skinnyPopup\").show(); }, 600)'

and this works to show only the popup I want with no delay:

这可以立即显示我想要的弹出窗口:

onmouseover='$(this).children(\".skinnyPopup\").show()'

but the combination does not:

但组合不会:

onmouseover='setTimeout(function() { $(this).children(\".skinnyPopup\").show(); }, 600)'

Any help would be appreciated. Thanks!

任何帮助,将不胜感激。谢谢!

采纳答案by Nick Craver

You need to define what thisis when it executes, something like this would work:

你需要定义什么this时候执行,这样的事情会起作用:

setTimeout($.proxy(function() { $(this).children(".skinnyPopup").show(); }, this), 600)

Or just use .delay(), like this:

或者只是使用.delay(),像这样:

$(this).children(".skinnyPopup").delay(600).show(0);

Both of the above are quick fixes, I suggest you move away from inline handlers and check out an unobtrusivemethod (see this answerby Russ Camfor some great reasons), for example:

上述两种是快速修复,我建议你从内联处理搬走,并检查了一个不显眼的方法(见本答案拉斯凸轮一些伟大的原因),例如:

$(function() {
  $('selector').mouseover(function() {
    $(this).children(".skinnyPopup").delay(600).show(0);
  });
});

回答by Cristian Sanchez

It's because thisis bound to the global context, not the element. Use something like the following instead:

这是因为this绑定到全局上下文,而不是元素。使用类似以下内容:

// put this in your document head -- replace element with a selector for the elements you want
$(function () {
    $(element).bind("mouseover", function () {
       var e = $(this);
       setTimeout(function () { e.children(".skinnyPopup").show(); }, 600);
    });
});

If you're adamant about inline event handlers, the following should also work:

如果您坚持使用内联事件处理程序,以下内容也应该适用:

onmouseover='var self = this; setTimeout(function() { $(self).children(\".skinnyPopup\").show(); }, 600)'