js motion

1 simple motion (uniform)

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>

3.jpg4.jpg

2 from a prescribed motion (uniform)

5.jpg

js code:

<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.

6.jpg

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

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

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

1.png

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 (the getStyle (Obox, 'left')> = totalDistance) {
console.log ( 'I do not perform a'); 
obox.style.left = totalDistance + 'px'; 
the clearInterval (obox.timer); 
} 
}, 30); 
} 
// Get style packaging methods without px unit 
the getStyle function (ELE, style) { 
    the let Result = ele.currentStyle ele.currentStyle [style]:? the getComputedStyle (ELE, null) [style]; 
    return the parseInt (Result); 
}


Guess you like

Origin blog.51cto.com/11871779/2404410