使用Javascript将HTML元素平滑地滚动到特定方向

时间:2015-11-28 08:50:50

标签: javascript html

我要做的就是这样做,如果你点击一个按钮(假设"滚动到左边"),它会开始滚动到左边,直到我按下另一个按钮才会停止按钮(a"停止"按钮)停止它。

function co() {
  coo=document.getElementById('tar');
  var x = coo.style.left;
  var y=(x+=10);
  coo.style.left=y+'px';
}
div {
  position:absolute;
  background-color:orange;
  border-radius:50%;
  width:100px;
  height:100px;
  transition-duration:2s;
}

body {
  width:100%;
  height:100%;
}

.plus {
  z-index:2;
  position:absolute;
  background-color:#CCC;
  right:15px;
  bottom:10px;
}
<body >
  <div id="tar"></div>
  <button class="plus" onClick="co()">Plus this</button>
</body>

1 个答案:

答案 0 :(得分:2)

只需使用setInterval在循环中重复您的函数,并使用clearInterval取消

此外,您可能希望阻止在动画运行时再次单击此项。

代码段

&#13;
&#13;
var cog;

function co() {
  // the first run need not have a delay
  cot();
  cog = setInterval(cot, 500)
}

function nco() {
  clearInterval(cog)
}

function cot() {
  var coo = document.getElementById('tar');
  var x = window.getComputedStyle(coo, null).left;
  var y = Number(x.replace('px', '')) + 100;
  coo.style.left = y + 'px';
}
&#13;
div#tar {
  left: 10px;
  position: absolute;
  background-color: orange;
  border-radius: 50%;
  width: 100px;
  height: 100px;
  transition-duration: 0.5s;
  transition-timing-function: linear;
}
body {
  width: 100%;
  height: 100%;
}
.plus {
  z-index: 2;
  position: absolute;
  right: 15px;
  bottom: 10px;
}
&#13;
<body>
  <div id="tar"></div>
  <div class='plus'>
    <button onClick="co()">Plus this</button>
    <button onClick="nco()">Stop</button>
  </div>
</body>
&#13;
&#13;
&#13;