打开和悬停不一起工作

on and hover not working together

本文关键字:一起 工作 悬停      更新时间:2023-09-26

My jquery code它不起作用时

   $("a").on("hover",function(){$(this).css("background","#ccc");},function(){$(this).css("background","#fff")});

但是在工作时

$("a").hover(function(){$(this).css("background","#ccc");},function(){$(this).css("background","#fff")});

如何使其与悬停一起使用

如果悬停.on()它看起来像

$("a").on('hover', function(e) {
  if(e.type =='mouseenter') {
   // code for mouseenter
  } else {
   // code for mouseleave
  }
});

但是对于.hover()来说,接受两个函数,第一个用于mouseenter,第二个用于mouseleave

$('a').hover(
  // for mouseenter
  function() {
  },
  // for mouseleave
  function() {
  }
);

因此,如果您想使用.on()那么您的代码将:

$("a").on('hover', function(e) {
  if(e.type =='mouseenter') {
     // code for mouseenter
     $(this).css("background","#ccc");
  } else {
     // code for mouseleave
     $(this).css("background","#fff")
  }
});

如果您想分别绑定mouseentermouseleave@ThiefMaster评论,您可以尝试:

$('a')
     .mouseenter(function() {
        $(this).css('background', '#ccc');
      })
     .mouseleave(function() {
         $(this).css('background', '#fff');
      });

或使用您可以执行的操作.on()

$('a').on({
  mouseenter: function() {
     $(this).css('background', '#ccc');
  },
  mouseleave: function() {
     $(this).css('background', '#fff');
  }
});

这是一个现场演示

和代码

$("a").on('hover', function(e) {
  if(e.type =='mouseenter') {
      // do something when mouse enter
      alert("mouse enter");
  } else {
      // do something when mouse leave
      alert("mouse leave");
  }
});​

悬停是mouseentermouseleave事件的快捷方式。因此,您可以使用类似方式绑定那些

$("a").on({ 
           mouseenter: function(){$(this).css("background","#ccc");},
           mouseleave: function(){$(this).css("background","#fff");}
         });