jQuery - How to remove event handler only while an animation or function is running?

痴心易碎 提交于 2019-12-12 23:51:34

问题


I am attempting to create an image gallery. At the bottom I have a strip of thumbnails these thumbnails slide left and right when you click an arrow but if you click the arrow multiple times it ques the function.

I would like to remove the click handler while the function is run, then replace it again.

On a side note, my thumbnail scroller uses margin-left to animate, is it possible to use scrollTo or similar, to move an element a specific amount, horizontally, so if the thumbnails change size, it would still work?


回答1:


There are many ways to do this. The easiest way is not to remove the click handler, but simply do nothing in the callback if it's animating already, eg:

$('.thumb').click(function() {
    if ($('#thumb-strip:animated').size() != 0)
        return;

    /* else animate #thumb-strip */
});

If you want to remove the click handler, and add it before, just do this:

var animateHandler = function() {
    var params = {}; // animate params
    $('.thumb').unbind('click', animateHandler); // unbind the click handler
    $('#thumb-strip').animate(params, function() {
        $('.thumb').click(animateHandler); // re-bind the click handler when animation is done
    });
};
$('.thumb').click(animateHandler);

Needless to say, the first way is simpler.

However what I usually do is not prevent the click event from happening, because the user won't expect that, but I also want to get rid of the queuing of animations. So what you can do is allow the user to click a thumb, and make it instantly animate to the new place with stop:

$('.thumb').click(function() {
    var params = {}; // animate params
    $('#thumb-strip').stop().animate(params);
});

This is the simplest and most intuitive solution.

And to answer your second question, you can use $(this).position() to get the thumb's relative position to the parent, and then animate based on that.



来源:https://stackoverflow.com/questions/3438426/jquery-how-to-remove-event-handler-only-while-an-animation-or-function-is-runn

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