1 简单运动(匀速)

box{    width: 100px;    height: 100px;    background-color: #ccc;    position: absolute;    top:200px;    left: 0;}<script type="text/javascript">    var obtn = document.querySelector('button');    var obox = document.querySelector('.box');    // 设置速度    var speed = 10;    obtn.onclick=function(){    // 1 先清除掉定时器    clearInterval(obox.timer);        obox.timer = setInterval(function(){        obox.style.left = obox.offsetLeft + speed + 'px'    },30);}</script>

2 指定运动的距离(匀速)

js代码:

<script type="text/javascript">    var obtn = document.querySelector('button');    var obox = document.querySelector('.box');    var totalDistance = 500;    // 设置速度    var speed = 10;    obtn.onclick = function() {    // 1 先清除掉定时器    clearInterval(obox.timer);    obox.timer = setInterval(function() {    obox.style.left = obox.offsetLeft + speed + 'px'    if(getStyle(obox,'left') >= totalDistance){    // 已经到达目的地了    obox.style.left = totalDistance + 'px';    // 同时我们还需要清除掉定时器    clearInterval(obox.timer);    }    }, 30);}// 封装获取样式的方法  不带px单位的function getStyle(ele, style) {    let result = ele.currentStyle ? ele.currentStyle[style] : getComputedStyle(ele, null)[style];    return parseInt(result);}</script>

3 缓冲运动(速度由快到慢,直至停止)

缓冲运动的原理: 速度由距离决定。即: 距离越大速度越大,距离越近,速度越小,直至为0.

4 加速运动(速度由慢到快,直至到达终点)

加速运动和缓冲运动相反,代码也不需要做过多的修改

原理:根据移动的距离来设置速度,也就是正比关系

var obtn = document.querySelector('button');var obox = document.querySelector('.box');var totalDistance = 500;// 设置速度var speed = null;obtn.onclick = function() {// 1 先清除掉定时器clearInterval(obox.timer);obox.timer = setInterval(function() {// 1 获取当前运动的距离var curPosition = getStyle(obox,'left');// 2 speed是变化的 动态计算speed = (curPosition / 10)||1;// 对speed进行取整操作// ceil:向上取整// floor: 向下取整// 3 *需要对speed进行取整 否则达不到临界值speed = speed > 0? Math.ceil(speed):Math.floor(speed);obox.style.left = obox.offsetLeft + speed + 'px';console.log(speed);if(getStyle(obox,'left') >= totalDistance){console.log('我执行了没');obox.style.left = totalDistance + 'px';clearInterval(obox.timer);}}, 30);}// 封装获取样式的方法  不带px单位的function getStyle(ele, style) {    let result = ele.currentStyle ? ele.currentStyle[style] : getComputedStyle(ele, null)[style];    return parseInt(result);}