美文网首页
1原生JS的animate运动

1原生JS的animate运动

作者: pingping_log | 来源:发表于2017-09-01 19:17 被阅读0次
  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在取值时会进行四舍五入(原因是,像素的小数是没有意义的)

相关文章

网友评论

      本文标题:1原生JS的animate运动

      本文链接:https://www.haomeiwen.com/subject/mjorkxtx.html