jQuery - how to use stopPropagation()

浪尽此生 提交于 2019-12-06 16:57:16

问题


I've done this before, but I'm having trouble getting this to work...

I need the following jquery to have a .stopPropagation function, so the animation won't go crazy if the user hovers over three elements too quickly!

    $(function () {
            var tabContainers = $('div.subMenu > div');
            tabContainers.hide();

            $('.mainMenuDiv a').hover(
            function (e) {
                tabContainers.filter(this.hash).slideDown();
                e.stop();
            },
            function(e){
                tabContainers.filter(this.hash).slideUp();
                e.stopPropagation();
            });
    });

回答1:


Sounds like you are looking for the stop function that cancels any incomplete animations.

$('.mainMenuDiv a').hover(
    function (e) {
        tabContainers.filter(this.hash).stop().slideDown();
    },
    function(e){
        tabContainers.filter(this.hash).stop().slideUp();
    }
);

or if you'd like any in-progress animation(s) to be "rolled back" try:

$('.mainMenuDiv a').hover(
    function (e) {
        tabContainers.filter(this.hash).stop(true, true).slideDown();
    },
    function(e){
        tabContainers.filter(this.hash).stop(true, true).slideUp();
    }
);

Check out the docs for more info.




回答2:


Be carefull when using stopPropagation() and stopImmediatePropagation() as if they were the same thing:

  • The Event.stopPropagation() method prevents the event object from moving on to the next node, but only after any other event listeners on the current node are allowed to execute.

  • The Event.stopImmediatePropagation() method also prevents the event object from moving on to the next node, but does not allow any other event listeners on the current node to execute.




回答3:


$(function () {

        var tabContainers = $('div.subMenu > div');
        tabContainers.hide();

        $('.mainMenuDiv a').hover(function () {

            tabContainers.filter(this.hash).dequeue().slideDown();

        },function () {

            tabContainers.filter(this.hash).dequeue().slideUp();

        });

});

Hope that this helps. ;) Events “bubble up” from the child element to all its parents, and you would event.stopPropragation(); or event.stopImmediatePropagation(). However to stop animation you dequeue().




回答4:


I could be wrong, but this might work:

$(function () {
    var tabContainers = $('div.subMenu > div');
    tabContainers.hide();
    $('.mainMenuDiv a').hover(function() {
        tabContainers.filter(this.hash).stop().slideDown();
    },function() {
        tabContainers.filter(this.hash).stop().slideUp();
    });
});


来源:https://stackoverflow.com/questions/1489232/jquery-how-to-use-stoppropagation

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