我一直在尝试让侧边栏根据点击左右滑动。
我确实尝试过切换,但无法使其正常工作。
我现在已经尝试了这段代码,第一次单击时它可以工作,但是一旦单击,由于某种原因,再次单击时它就不起作用:
$('.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');
});
关于jquery - 为什么这个 jquery 动画不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19476103/