jquery hover once?

匿名 (未验证) 提交于 2019-12-03 08:48:34

问题:

What's the jquery way to make hover function execute once and then stop?

.one() didnt work..

$(".button-color-2").hover(   function (){    dosmth();  });

thank you

回答1:

Hover binds the handlers for Mouse Enter and Mouse Leave event and is not an event on its own. Hence, in order to have the same effect as Hover, you will have two binds that will trigger once.

$(".button-color-2").one("mouseenter mouseleave", function(e){ dosmth(); });

If you want to do different things on mouseenter and mouseleave, then bind two different handlers

$(".button-color-2").one("mouseenter", function(e){ dosmth1(); }).one("mouseleave", function(e){ dosmth2(); });

The other option would be to use Hover and then unbind it once you are done.

$('.button-color-2').hover(function() { dosmth(); $(this).unbind('mouseenter mouseleave') });


回答2:

If this did not work:

$(".button-color-2").one('hover', function() {     dosmth(); });

then try this which will execute the hover once and then unbind the hover event:

$('.button-color-2').bind('hover', function(event) {   dosmth();   $(this).unbind(event); });


回答3:

If you just wrapped that piece of code into .one(), you didn't do it right.

With your upper function, you are assigning hover event, not executing it. So you have to use $.one() like this:

$('.button-color-2').one('hover', function()       dosth(); );


回答4:

This is an old thread, but here is how I was able to accomplish this. I created a counter that incremented after the effect ran on a mouseenter and used an if statement to see if the counter was greater than 1. If the counter was greater than 1, just make another else statement that breaks out of it entirely (this is to keep it from continuously doing the effect). You'll also need a mouseleave method to reset your counter back to 0. Here is the code I used:

    $("#mydiv").mouseenter(function(){         if (counter < 1){             $(this).effect("pulsate", { times:1 }, 300);             counter = counter + 1;             return;         }         else{             return;         }     });     $("#mydiv").mouseleave(function(){         counter = 0;         return;     });

If you want to see it working, here is the page: http://webpages.marshall.edu/~glasser1/jquery.html

hover over the white box and it will pulse once.

edit: I forgot to add that you need to initialize your variable counter outside of the function so that it's global and set to zero.



转载请标明出处:jquery hover once?
文章来源: jquery hover once?
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!