js中的運動

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>

3.jpg4.jpg

2 指定運動的距離(勻速)

5.jpg

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.

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(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);
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章