简体   繁体   English

使div做-200px多次?

[英]make div do -200px multiple times?

I am trying to move a div -200px from his original position when I press a button. 当我按下按钮时,我试图将div -200px从其原始位置移开。 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. 这段代码(我想,如果我错了,请纠正我。)确实将属性ONCE设置为-200px。 Is there any way I can make this do -200px from every new starting position? 有什么办法可以让我在每个新的起始位置都做到-200px?

Since you have used the jquery-animate tag, I shall presume you have jQuery. 由于您使用了jquery-animate标记,因此我假设您使用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. 可以根据需要调用此函数,如果要滑动元素或其他元素,可以在元素上添加一个CSS过渡。 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: 如果您的元素是绝对元素,请尝试使用Left而不是margin-left,或者您可以尝试使用jQuery:

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

Using pure javascript: 使用纯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: 使用jQuery,只需将函数更改为:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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