如何使按钮在每次点击时保持移动?

时间:2017-07-24 09:15:26

标签: javascript html5

我已经制作了这个代码,让按钮每次点击都会向左移动..但它只移动一次并停止..请帮我找错误

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
  <style>
    #myBtn {
      position: absolute;
    }
  </style>
</head>

<body>

  <button type="button" id="myBtn" onclick="myFunction()">Set left position to 
    100 px</button>

  <script>
    function myFunction() {
      document.getElementById("myBtn").style.left = "100px";
    }
  </script>

</body>

</html>

4 个答案:

答案 0 :(得分:2)

function myFunction() {

  var currentLeft = parseInt(document.getElementById("myBtn").style.left) || 0;

  document.getElementById("myBtn").style.left = currentLeft + 100 + "px";
}
#myBtn {
  position: absolute;
}
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
</head>

<body>

  <button type="button" id="myBtn" onclick="myFunction()">Set left position to 
        100 px</button>


</body>

</html>

获取当前左侧位置,增加100并分配给元素。

document.getElementById("myBtn").style.left = parseInt(document.getElementById("myBtn").style.left) + 100 + "px";

答案 1 :(得分:0)

我认为你只是将它设置为100px的静态值。你应该这样做,以便在每次点击时,这个值逐渐减少或增加,如:

1 click - 100px
2 click - 80px
3 click - 60px

依旧......

我没有太多的HTML知识,但我想了很多。

答案 2 :(得分:0)

每次点击时,您需要确定按钮的位置:

var rec = document.getElementById("myBtn").getBoundingClientRect();
document.getElementById("myBtn").style.left = 100+rec.left+'px';

答案 3 :(得分:0)

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
  <style>
    #myBtn {
      position: absolute;
    }
  </style>
</head>

<body>

  <button type="button" id="myBtn" onclick="myFunction()">Set left position to 
    100 px</button>

  <script>
    function myFunction() {

      var position = document.getElementById("myBtn").style.left ? document.getElementById("myBtn").style.left : "0px";
      position = parseInt(position.substring(0, position.length - 2)); 
      document.getElementById("myBtn").style.left = position + 100 + "px";
    }
  </script>

</body>

</html>