JavaScript能够控制物体运动(DOM)

运动的方式也有许多种,例如说匀速运动,缓冲运动

匀速运动

如图点击按钮后让黄色小方块运动到距离它300px的位置。

思路

​ 我们把黄色方块的left增加7px,那么黄色方块就向右移动了7px。如果我们每隔30毫秒让黄色方框向右移动7px,那么看起来黄色方块看起来就在运动了。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
var a = document.getElementsByClassName('a')[0];
var btn = document.getElementsByClassName('btn')[0];
btn.onclick = function () {
startMove()
}
function startMove() {
var timer = setInterval(function () {
a.style.left = a.offsetLeft + 6 + 'px';
if (a.offsetLeft >= 300) {
clearInterval(timer)
a.style.left = 300;
}
}, 30)
}
越点越快的bug

实际上有这个demo有许多问题,例如说疯狂点击按钮,计时器会叠加,方块运动速度飞快

那就弄一个全局的定时器,每次点击的时候清理就好了啊

缓冲运动

缓冲运动就是在停止前速度越来越慢,直到完全停下来。

思路

​ 缓冲运动的一个关键是控制速度,距离离终点越近速度越低。因此我们可以把速度设置为终点距离 - 物体距离 ,当相减为0的时候说明已经到达终点。

实现
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
var a = document.getElementsByClassName('a')[0];
var btn = document.getElementsByClassName('btn')[0];
btn.onclick = function(){
startMove(a,400);
}
var timer = null;

function startMove(dom, target) {
clearInterval(timer);
var isSpeed = null;
timer = setInterval(function () {
isSpeed = (target - dom.offsetLeft) / 10;
isSpeed = isSpeed > 0 ? Math.ceil(isSpeed) : Math.floor(isSpeed);
if (target == dom.offsetLeft) {
clearInterval(timer);
console.log('over');
} else {
dom.style.left = dom.offsetLeft + isSpeed + 'px';
}
}, 30)
}

弹出运动框

也不说啥了直接看图吧。思路其实也简单,当鼠标进入的时候触发 onmouseenter事件。

同时触发startMove()事件。

点击渐变消失

思想
1. 思想也跟之前一样,`isSpeed`变量为渐变速度。
 2. 这里需要有一个`getStyle`函数,用来获取dom的透明度。
实现
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
var timer = null;
var wrapper = document.getElementsByClassName("wrapper")[0];
wrapper.onmouseenter = function () {
startMove(this, 0);
}


wrapper.onmouseleave = function () {
startMove(this, 0.2)
}

function getStyle(dom, attr) {
if (window.getComputedStyle) {
return window.getComputedStyle(dom, null)[attr];
} else {
return dom.currentStyle[attr];
}
}

function startMove(dom, target) {
clearInterval(dom.timer);
var isSpeed = null;
dom.timer = setInterval(function () {
iCur = parseFloat(getStyle(dom, 'opacity')) * 100;
isSpeed = (target - iCur) / 17;
isSpeed = isSpeed > 0 ? Math.ceil(isSpeed) : Math.floor(isSpeed);
if (iCur == target) {
clearInterval(dom.timer);
} else {
dom.style.opacity = (iCur + isSpeed) / 100;
}
}, 30)
}

评论