是否可以使用 jQuery .on 并悬停?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9827095/
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-08-27 11:21:17  来源:igfitidea点击:

Is it possible to use jQuery .on and hover?

jquery

提问by Ryre

I have a <ul>that is populated with javascript after the initial page load. I'm currently using .bindwith mouseoverand mouseout.

我有一个<ul>在初始页面加载后填充了 javascript。我目前正在使用.bindwithmouseovermouseout

The project just updated to jQuery 1.7 so I have the option to use .on, but I can't seem to get it to work with hover. Is it possible to use .onwith hover?

该项目刚刚更新到 jQuery 1.7,所以我可以选择使用.on,但我似乎无法让它与hover. 是否有可能使用.onhover

EDIT: The elements I'm binding to are loaded with javascript after the document loads. That's why I'm using onand not just hover.

编辑:我绑定到的元素在文档加载后加载了 javascript。这就是为什么我使用on而不仅仅是hover.

回答by Sethen

(Look at the last edit in this answer if you need to use .on()with elements populated with JavaScript)

如果您需要.on()与用 JavaScript 填充的元素一起使用,请查看此答案中的最后一次编辑

Use this for elements that are not populated using JavaScript:

将此用于未使用 JavaScript 填充的元素:

$(".selector").on("mouseover", function () {
    //stuff to do on mouseover
});

.hover()has it's own handler: http://api.jquery.com/hover/

.hover()有它自己的处理程序:http: //api.jquery.com/hover/

If you want to do multiple things, chain them in the .on()handler like so:

如果你想做多件事,.on()像这样将它们链接到处理程序中:

$(".selector").on({
    mouseenter: function () {
        //stuff to do on mouse enter
    },
    mouseleave: function () {
        //stuff to do on mouse leave
    }
});

According to the answers provided below you can use hoverwith .on(), but:

根据下面提供的答案,您可以使用hoverwith .on(),但是:

Although strongly discouraged for new code, you may see the pseudo-event-name "hover" used as a shorthand for the string "mouseenter mouseleave". It attaches a single event handler for those two events, and the handler must examine event.type to determine whether the event is mouseenter or mouseleave. Do not confuse the "hover" pseudo-event-name with the .hover() method, which accepts one or two functions.

尽管强烈建议不要使用新代码,但您可能会看到伪事件名称“hover”用作字符串“mouseenter mouseleave”的简写。它为这两个事件附加了一个事件处理程序,处理程序必须检查 event.type 以确定事件是 mouseenter 还是 mouseleave。不要将“悬停”伪事件名称与接受一两个函数的 .hover() 方法混淆。

Also, there are no performance advantages to using it and it's more bulky than just using mouseenteror mouseleave. The answer I provided requires less code and is the proper way to achieve something like this.

此外,使用它没有性能优势,而且它比仅使用mouseenteror更笨重mouseleave。我提供的答案需要较少的代码,并且是实现此类目标的正确方法。

EDIT

编辑

It's been a while since this question was answered and it seems to have gained some traction. The above code still stands, but I did want to add something to my original answer.

自从回答这个问题以来已经有一段时间了,它似乎获得了一些牵引力。上面的代码仍然有效,但我确实想在我的原始答案中添加一些内容。

While I prefer using mouseenterand mouseleave(helps me understand whats going on in the code) with .on()it is just the same as writing the following with hover()

虽然我更喜欢使用mouseentermouseleave(帮助我理解代码中发生了什么),.on()但它与编写以下内容相同hover()

$(".selector").hover(function () {
    //stuff to do on mouse enter
}, 
function () {
    //stuff to do on mouse leave
});

Since the original question did ask how they could properly use on()with hover(), I thought I would correct the usage of on()and didn't find it necessary to add the hover()code at the time.

由于最初的问题确实询问了他们如何正确使用on()with hover(),我想我会更正 的用法on()并且当时没有发现有必要添加hover()代码。

EDIT DECEMBER 11, 2012

编辑 2012 年 12 月 11 日

Some new answers provided below detail how .on()should work if the divin question is populated using JavaScript. For example, let's say you populate a divusing jQuery's .load()event, like so:

下面提供的一些新答案详细说明了.on()如果div使用 JavaScript 填充有问题,应该如何工作。例如,假设您div使用 jQuery 的.load()事件填充 a ,如下所示:

(function ($) {
    //append div to document body
    $('<div class="selector">Test</div>').appendTo(document.body);
}(jQuery));

The above code for .on()would not stand. Instead, you should modify your code slightly, like this:

上面的代码是.on()站不住脚的。相反,您应该稍微修改您的代码,如下所示:

$(document).on({
    mouseenter: function () {
        //stuff to do on mouse enter
    },
    mouseleave: function () {
        //stuff to do on mouse leave
    }
}, ".selector"); //pass the element as an argument to .on

This code will work for an element populated with JavaScript after a .load()event has happened. Just change your argument to the appropriate selector.

此代码适用于.load()事件发生后用 JavaScript 填充的元素。只需将您的参数更改为适当的选择器即可。

回答by cazzer

None of these solutions worked for me when mousing over/out of objects created after the document has loaded as the question requests. I know this question is old but I have a solution for those still looking:

当将鼠标移到/移出在文档按照问题请求加载后创建的对象时,这些解决方案都不适合我。我知道这个问题很老,但我为那些仍在寻找的人提供了解决方案:

$("#container").on('mouseenter', '.selector', function() {
    //do something
});
$("#container").on('mouseleave', '.selector', function() {
    //do something
});

This will bind the functions to the selector so that objects with this selector made after the document is ready will still be able to call it.

这会将函数绑定到选择器,以便在文档准备好后使用此选择器创建的对象仍然能够调用它。

回答by Jon McIntosh

I'm not sure what the rest of your Javascript looks like, so I won't be able to tell if there is any interference. But .hover()works just fine as an event with .on().

我不确定你的 Javascript 的其余部分是什么样的,所以我无法判断是否有任何干扰。但.hover()作为事件与.on().

$("#foo").on("hover", function() {
  // disco
});

If you want to be able to utilize its events, use the returned object from the event:

如果您希望能够利用其事件,请使用事件返回的对象:

$("#foo").on("hover", function(e) {
  if(e.type == "mouseenter") {
    console.log("over");
  }
  else if (e.type == "mouseleave") {
    console.log("out");
  }
});

http://jsfiddle.net/hmUPP/2/

http://jsfiddle.net/hmUPP/2/

回答by Tigin

jQuery hover function gives mouseover and mouseout functionality.

jQuery 悬停功能提供鼠标悬停和鼠标移出功能。

$(selector).hover(inFunction,outFunction);

$(selector).hover(inFunction,outFunction);

$(".item-image").hover(function () {
    // mouseover event codes...
}, function () {
    // mouseout event codes...
});

Source: http://www.w3schools.com/jquery/event_hover.asp

来源:http: //www.w3schools.com/jquery/event_hover.asp

回答by KryptoniteDove

Just surfed in from the web and felt I could contribute. I noticed that with the above code posted by @calethebrewer can result in multiple calls over the selector and unexpected behaviour for example: -

刚刚从网上冲浪,觉得我可以做出贡献。我注意到@calethebrewer 发布的上述代码可能会导致对选择器的多次调用和意外行为,例如:-

$(document).on('mouseover', '.selector', function() {
   //do something
});
$(document).on('mouseout', '.selector', function() {
   //do something
});

This fiddle http://jsfiddle.net/TWskH/12/illustraits my point. When animating elements such as in plugins I have found that these multiple triggers result in unintended behavior which may result in the animation or code being called more than is necessary.

这个小提琴http://jsfiddle.net/TWskH/12/说明了我的观点。在为插件中的元素设置动画时,我发现这些多个触发器会导致意外行为,这可能导致动画或代码被调用的次数超过必要的次数。

My suggestion is to simply replace with mouseenter/mouseleave: -

我的建议是简单地用 mouseenter/mouseleave 替换:-

$(document).on('mouseenter', '.selector', function() {
   //do something
});
$(document).on('mouseleave', '.selector', function() {
   //do something
});

Although this prevented multiple instances of my animation from being called, I eventually went with mouseover/mouseleave as I needed to determine when children of the parent were being hovered over.

尽管这阻止了我的动画的多个实例被调用,但我最终还是使用了鼠标悬停/鼠标离开,因为我需要确定何时将父母的孩子悬停在上面。

回答by Code Maverick

You can you use .on()with hoverby doing what the Additional Notes section says:

您可以通过执行附加说明部分的说明来使用.on()with hover

Although strongly discouraged for new code, you may see the pseudo-event-name "hover" used as a shorthand for the string "mouseenter mouseleave". It attaches a single event handler for those two events, and the handler must examine event.type to determine whether the event is mouseenter or mouseleave. Do not confuse the "hover" pseudo-event-name with the .hover() method, which accepts one or two functions.

尽管强烈建议不要使用新代码,但您可能会看到伪事件名称“hover”用作字符串“mouseenter mouseleave”的简写。它为这两个事件附加了一个事件处理程序,处理程序必须检查 event.type 以确定事件是 mouseenter 还是 mouseleave。不要将“悬停”伪事件名称与接受一两个函数的 .hover() 方法混淆。

That would be to do the following:

那将是做以下事情:

$("#foo").on("hover", function(e) {

    if (e.type === "mouseenter") { console.log("enter"); }
    else if (e.type === "mouseleave") { console.log("leave"); }

});


EDIT (note for jQuery 1.8+ users):

编辑(jQuery 1.8+ 用户注意):

Deprecated in jQuery 1.8, removed in 1.9: The name "hover" used as a shorthand for the string "mouseenter mouseleave". It attaches a single event handler for those two events, and the handler must examine event.type to determine whether the event is mouseenter or mouseleave. Do not confuse the "hover" pseudo-event-name with the .hover() method, which accepts one or two functions.

在 jQuery 1.8 中弃用,在 1.9 中删除:名称“hover”用作字符串“mouseenter mouseleave”的简写。它为这两个事件附加了一个事件处理程序,处理程序必须检查 event.type 以确定事件是 mouseenter 还是 mouseleave。不要将“悬停”伪事件名称与接受一两个函数的 .hover() 方法混淆。

回答by webmaster01

$("#MyTableData").on({

 mouseenter: function(){

    //stuff to do on mouse enter
    $(this).css({'color':'red'});

},
mouseleave: function () {
    //stuff to do on mouse leave
    $(this).css({'color':'blue'});

}},'tr');

回答by user2386291

You can provide one or multiple event types separated by a space.

您可以提供一种或多种由空格分隔的事件类型。

So hoverequals mouseenter mouseleave.

所以hover等于mouseenter mouseleave

This is my sugession:

这是我的建议:

$("#foo").on("mouseenter mouseleave", function() {
    // do some stuff
});

回答by Sanne

If you need it to have as a condition in an other event, I solved it this way:

如果你需要它作为其他事件的条件,我是这样解决的:

$('.classname').hover(
     function(){$(this).data('hover',true);},
     function(){$(this).data('hover',false);}
);

Then in another event, you can easily use it:

然后在另一个事件中,您可以轻松使用它:

 if ($(this).data('hover')){
      //...
 }

(I see some using is(':hover')to solve this. But this is not (yet) a valid jQuery selector and does not work in all compatible browsers)

(我看到一些人is(':hover')用来解决这个问题。但这不是(还)有效的 jQuery 选择器,并且不适用于所有兼容的浏览器)

回答by Chris Marisic

The jQuery plugin hoverIntent http://cherne.net/brian/resources/jquery.hoverIntent.htmlgoes much further than the naive approaches listed here. While they certainly work, they might not necessarily behave how users expect.

jQuery 插件 hoverIntent http://cherne.net/brian/resources/jquery.hoverIntent.html比这里列出的幼稚方法更进一步。虽然它们确实有效,但它们的行为不一定符合用户的期望。

The strongest reason to use hoverIntent is the timeoutfeature. It allows you to do things like prevent a menu from closing because a user drags their mouse slightly too far to the right or left before they click the item they want. It also provides capabilities for not activating hover events in a barrage and waits for focused hovering.

使用 hoverIntent 的最大原因是超时功能。它允许您执行一些操作,例如防止菜单关闭,因为用户在单击他们想要的项目之前将鼠标稍微向右或向左拖得太远。它还提供了在弹幕中不激活悬停事件并等待聚焦悬停的功能。

Usage example:

用法示例:

var config = {    
 sensitivity: 3, // number = sensitivity threshold (must be 1 or higher)    
 interval: 200, // number = milliseconds for onMouseOver polling interval    
 over: makeTall, // function = onMouseOver callback (REQUIRED)    
 timeout: 500, // number = milliseconds delay before onMouseOut    
 out: makeShort // function = onMouseOut callback (REQUIRED)
};
$("#demo3 li").hoverIntent( config )

Further explaination of this can be found on https://stackoverflow.com/a/1089381/37055

对此的进一步解释可以在https://stackoverflow.com/a/1089381/37055上找到