在网页设计中,咱们常常使用jquery去响应鼠标的hover事件,和mouseover和mouseout事件有相同的效果,可是这其中其中如何使用on去绑定hover方法呢?如何用off取消绑定的事件呢?
1、如何绑定hover事件
先看如下代码,假设咱们给a标签绑定一个click和hover事件:
$(document).ready(function(){ $('a').on({ hover: function(e) { jquery
//Hover event handler 函数
alert("hover"); },spa
click: function(e) { // Click event handler设计
alert("click"); } }); seo
});
当点击a标签的时候,奇怪的事情发生了,其中绑定的hover事件彻底没有反应,绑定的click事件却能够正常响应。
可是若是换一种写法,好比:
$("a").hover(function(){ alert('mouseover'); }, function(){
alert('mouseout'); })
应该使用 mouseenter 和 mouseleave 这两个事件来代替,(这也是 .hover() 函数中使用的事件)
因此彻底能够直接像这样来引用:
$(document).ready(function(){ $('a').on({ mouseenter: function(e) {事件
//Hover event handler io
alert("mouseover"); }, mouseleave: function(e) {event
//Hover event handler function
alert("mouseout"); }, click: function(e) { cli
// Clickevent handler
alert("click"); } });
});
由于.hover()是jQuery本身定义的事件,是为了方便用户绑定调用mouseenter和mouseleave事件而已,它并不是一个真正的事件,因此固然不能当作.on()中的事件参数来调用。
2、如何取消hover事件
你们都知道,可使用off函数去取消绑定的事件,可是只能取消经过bind绑定的事件,jquery中的hover事件是比较特殊的,若是经过这种方式去绑定的事件,则没法取消。
$("a").hover(function(){ alert('mouseover'); }, function(){
alert('mouseout'); })
取消绑定的hover事件的正确方式:
$('a').off('mouseenter').unbind('mouseleave');