I want to add a margin-left css style to a div element when an event is triggered by the user clicking a button, and then remove it when the user clicks the button again.
This is the div element:
<div id="container" class="content">
Javascript should change it to:
<div id="container" class="content" style="margin-left:354px">
Ideally using an animation so it appears to slide left rather than jump.
Try this in the event listener:
var cont = document.getElementById("container");
cont.style.marginLeft = cont.style.marginLeft === "354px" ? "auto" "354px";
This doesn't animate it. You may consider using CSS for that:
#container {
transition: margin-left ease 500ms;
}
But if you want to support older browsers and IE9, go for soyuka's answer.
You should read the manual before posting such a question...
$('.content').animate({'margin-left':'354px'}, 1000);
//where 1000 is the animation time in ms
To roll back :
$('.content').animate({'margin-left':'auto'}); //or your previous value
尝试这个解决方案,我已经加入了JSBin: http : //jsbin.com/oyemen/1/edit
You can use jQuery.animate
along with the margin-left
css attribute. The second parameter of animate
is the duration (in milliseconds). There are a bunch of other settings to allow finer control of the animation (eg, easing-in or -out).
$('#container').animate({'margin-left':'354px'},3000);
and to move it back the opposite
$('#container').animate({'margin-left':'0px'},3000);
Live example: http://jsfiddle.net/xdpCs/1/
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.