簡體   English   中英

使div做-200px多次?

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

當我按下按鈕時,我試圖將div -200px從其原始位置移開。 現在,我希望能夠多次執行此操作。

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

這段代碼(我想,如果我錯了,請糾正我。)確實將屬性ONCE設置為-200px。 有什么辦法可以讓我在每個新的起始位置都做到-200px?

由於您使用了jquery-animate標記,因此我假設您使用jQuery。 在這種情況下,以下方法應該起作用:

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

可以根據需要調用此函數,如果要滑動元素或其他元素,可以在元素上添加一個CSS過渡。 祝您編碼愉快!

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;");
}

如果您的元素是絕對元素,請嘗試使用Left而不是margin-left,或者您可以嘗試使用jQuery:

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

使用純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> 

使用jQuery,只需將函數更改為:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM