简体   繁体   中英

make div do -200px multiple times?

I am trying to move a div -200px from his original position when I press a button. Now I want to be able to do this multiple times.

 function leftAnimate(){ original = document.getElementById("sliderzelf").setAttribute("style", "margin-left: -200px;"); } 

This piece of code ( I assume, correct me if Im wrong.) really sets the attribute ONCE to -200px. Is there any way I can make this do -200px from every new starting position?

Since you have used the jquery-animate tag, I shall presume you have jQuery. In which case the following should work:

function leftAnimate() {
    $("#sliderzelf").css("margin-left", "-=200");
}

call this function however you like, add a css transition on the element if you want it to slide or whatever. happy coding!

function leftAnimate(){
  var el = document.getElementById("section");
  var curMargin = window.getComputedStyle(el)['margin-left'].replace('px', '');
  var newPos = Number(curMargin - 200);
  original = el.setAttribute("style", "margin-left:" + newPos + "px;");
}

if you element is an absolute element, try use the Left instead margin-left, or You can try with jQuery:

function leftAnimate(){
        var actualPosition = $("#sliderzelf").css("left");
        original = document.getElementById("sliderzelf").setAttribute("style", "margin-left: " + (actualPosition - 200).toString() + "px;");
    }

Using pure javascript:

 function leftAnimate(){ //get the button var btn = document.getElementById("sliderzelf"); //get the current margin var currentMargin = btn.style.marginLeft.replace("px", ""); //calculate the new margin var newMargin = currentMargin - 200; //check if the new margin is valid (optional) if (newMargin >= 0) btn.setAttribute("style", "margin-left: " + newMargin + "px;") //set the new margin } 
 <button id="sliderzelf" style="margin-left: 600px" onclick="leftAnimate()"> Click me! </button> 

With jquery just change the function to:

 $("#sliderzelf").css('margin-left', '-= 200');

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM