jQuery - stop animation in progress (fadeOut) and show again when mouse enters/leaves quickly

假如想象 提交于 2019-12-10 19:21:44

问题


I have a <div> that when hovered over, will show some text. When the mouse leaves, the text fades out. However, if the mouse enters the <div> again before the fadeOut is complete, the text never shows again.

I am aware of hoverintent, but I'd prefer not to use it because of the slight perceived delay it gives to the mouseEnter/mouseLeave events.

Is there no way that, upon mouseEnter, it simply clears the fadeOut and shows the text again?

My current attempt using timeouts:

var timeouts = {};

$(document).ready(function(){
  $('#wrapper').hover(function(){
    clearTimeout(timeouts['test_hover']);
    $('#text').show();
  }, function(){
    timeouts['test_hover'] = setTimeout(function(){
      $('#text').fadeOut('slow');
    });
  });
});

jsbin: http://jsbin.com/upotuw/5

video: http://www.youtube.com/watch?v=7RLrz1bEQuU

--

EDIT: Issue was needing to pass both parameters to the stop() function: stop(true,true)

Final working code is as follows:

var timeouts = {};

$(document).ready(function(){
  $('#wrapper').hover(function(){
    clearTimeout(timeouts['test_hover']);
    $('#text').stop(true,true).show();
  }, function(){
    timeouts['test_hover'] = setTimeout(function(){
      $('#text').fadeOut('slow');
    });
  });
});

http://jsbin.com/upotuw/7


回答1:


You want to look into the JQuery stop() function:

http://api.jquery.com/stop/



来源:https://stackoverflow.com/questions/10175755/jquery-stop-animation-in-progress-fadeout-and-show-again-when-mouse-enters-l

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