jquery - 为什么这个 jquery 动画不起作用?

标签 jquery jquery-animate

我一直在尝试让侧边栏根据点击左右滑动。

我确实尝试过切换,但无法使其正常工作。

我现在已经尝试了这段代码,第一次单击时它可以工作,但是一旦单击,由于某种原因,再次单击时它就不起作用:

$('.pushbutton').on('click',function(){

        $('.left_sidebar, .footer').animate({left: "-320px"}, 800 );
        $('.main_body_right').animate({marginLeft: "25px"}, 800 );
        $('.pushbutton').animate({fontSize: "24px",fontWeight: "400",paddingTop: "3px"}, 500 );
        $('.pushbutton').html('+');
        $('.pushbutton').attr('class','pushbuttonplus');

    });

    $('.pushbuttonplus').on('click',function(){

        $('.left_sidebar, .footer').animate({left: "0px"}, 800 );
        $('.main_body_right').animate({marginLeft: "325px"}, 800 );
        $('.pushbuttonplus').animate({fontSize: "26px",fontWeight: "700",paddingTop: "0px"}, 500 );
        $('.pushbuttonplus').html('-');
        $('.pushbuttonplus').attr('class','pushbutton');

    });

最佳答案

因为您动态更改/添加/删除元素的类,所以选择器不会绑定(bind)到任何元素。

使用event delegation相反,因此您的事件将附加到正文上,但仅当匹配特定选择器时才如此。

引用:

When a selector is provided, the event handler is referred to as delegated. The handler is not called when the event occurs directly on the bound element, but only for descendants (inner elements) that match the selector. jQuery bubbles the event from the event target up to the element where the handler is attached (i.e., innermost to outermost element) and runs the handler for any elements along that path matching the selector.

代码:

$('body').on('click','.pushbutton', function () {

    alert("demo1")

    $('.left_sidebar, .footer').animate({
        left: "-320px"
    }, 800);
    $('.main_body_right').animate({
        marginLeft: "25px"
    }, 800);
    $('.pushbutton').animate({
        fontSize: "24px",
        fontWeight: "400",
        paddingTop: "3px"
    }, 500);
    $('.pushbutton').html('+');
    $('.pushbutton').attr('class', 'pushbuttonplus');

});

$('body').on('click','.pushbuttonplus', function () {

      alert("demo2")

    $('.left_sidebar, .footer').animate({
        left: "0px"
    }, 800);
    $('.main_body_right').animate({
        marginLeft: "325px"
    }, 800);
    $('.pushbuttonplus').animate({
        fontSize: "26px",
        fontWeight: "700",
        paddingTop: "0px"
    }, 500);
    $('.pushbuttonplus').html('-');
    $('.pushbuttonplus').attr('class', 'pushbutton');

});

演示:http://jsfiddle.net/IrvinDominin/wBBZm/

关于jquery - 为什么这个 jquery 动画不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19476103/

相关文章:

jquery - 使用 href ="#!/id"导航

javascript - 使用 jQuery 使 session 在长时间运行的过程中保持事件状态

javascript - 在焦点和 Tab 键按下时切换元素的类

jquery - 如何在关闭时删除所有 jQuery UI 对话框

jQuery - 当滑动面板显示时绝对定位的 div 的动画 'left' 位置

javascript - 最初隐藏一个 div 以供以后显示

jquery - float 父项导致 firefox 8 中的 jquery 性能停滞/滞后

javascript - 使用 jQuery 单击操作后重新启动功能

javascript - jQuery animate 在所有浏览器中都非常不稳定 - 带有 jpg 的 div 同时向上移动和淡入

javascript - Jquery animate 不是动画