Home > Article > Web Front-end > How to cancel hover event in jquery
Jquery method to cancel the hover event: 1. Bind a click and hover event to the a tag; 2. Use "$('a').unbind('mouseenter').unbind('mouseleave') ;" method can cancel the bound hover event.
The operating environment of this article: windows7 system, jquery version 3.2.1, DELL G3 computer
How to cancel the hover event with jquery?
The correct way to cancel and bind hover events in jquery
In web design, we often use jquery to respond to mouse hover events, mouseover and mouseout Events have the same effect, but how to use bind to bind the hover method? How to use unbind to unbind an event?
1. How to bind the hover event
First look at the following code. Suppose we bind a click and hover event to the a tag:
$(document).ready(function(){ $('a').bind({ hover: function(e) { // Hover event handler alert("hover"); }, click: function(e) { // Click event handler alert("click"); } }); });
When the a tag is clicked, something strange happens. The bound hover event does not respond at all, but the bound click event responds normally.
But if you change the writing method, for example:
$("a").hover(function(){ alert('mouseover'); }, function(){ alert('mouseout'); })
This code can run normally. Can't bind bind hover?
In fact, no, the two events mouseenter and mouseleave should be used instead (this is also the event used in the .hover() function)
So it can be quoted directly like this:
$(document).ready(function(){ $('a').bind({ mouseenter: function(e) { // Hover event handler alert("mouseover"); }, mouseleave: function(e) { // Hover event handler alert("mouseout"); }, click: function(e) { // Click event handler alert("click"); } }); });
Because .hover() is an event defined by jQuery itself, it is just for the convenience of users to bind and call mouseenter and mouseleave events. It is not a real event, so of course it cannot be used as an event parameter in .bind() to call.
2. How to cancel the hover event
As we all know, you can use the unbind function to cancel bound events, but you can only cancel events bound through bind. The hover event in jquery is quite special. If the event is bound in this way, it cannot be canceled.
$("a").hover(function(){ alert('mouseover'); }, function(){ alert('mouseout'); })
The correct way to cancel the bound hover event:
$('a').unbind('mouseenter').unbind('mouseleave');
3. Summary
In fact, for these issues, you can refer to the official jquery instructions Documentation, but few people have read it. Most tutorials on the Internet only explain how to use this method and only achieve the goal. There is no in-depth understanding of why it is written in this way?
Recommended learning: "jquery video tutorial"
The above is the detailed content of How to cancel hover event in jquery. For more information, please follow other related articles on the PHP Chinese website!