1原生JS的animate运动

2017-09-01  本文已影响0人  pingping_log
  1. 获取要运动的box

  2. 清除定时器,防止连续点击按钮时,加速运动

  3. 获取当前box的offsetlLeft值,并确定step的步伐,由于目前是正数所以向上取整就好

  4. 更新当前current值(每次执行时都加上step值)

  5. 当目标值等于当前值时,清除定时器

* {

margin: 0;

padding: 0;

}

#box {

width: 100px;

height: 100px;

background: pink;

position: absolute;

}

<button id = "btn">运动到400</button>
<div id = "box"></div>

var btn = document.getElementById('btn');

var box = document.getElementById('box');

var timer = null;

btn.onclick = function () {

clearInterval(timer);

timer = setInterval(function () {

var current = box.offsetLeft;

var step = (400 - current) / 10;

step = Math.ceil(step);

current += step;

box.style.left = current + 'px';

if(current == 400) {

clearInterval(timer);

}

},20);

}

offsetLeft在取值时会进行四舍五入(原因是,像素的小数是没有意义的)

上一篇 下一篇

猜你喜欢

热点阅读