html代码
<div id="box"></div>
css代码
* {
margin: 0;
padding: 0;
}
#box {
width: 100px;
height: 100px;
background: red;
position: absolute;
}
JS代码
加速运动
var oBox = document.getElementById("box");
document.onclick = function () {
var l = 0;
setInterval(function () {
l++;
oBox.style.left = oBox.offsetLeft + l + 'px';
}, 30)
}
减速运动 var oBox = document.getElementById("box");
document.onclick = function () {
var l = 30;
setInterval(function () {
l--;
oBox.style.left = oBox.offsetLeft + l + 'px';
}, 30)
}
弹性运动
var oBox = document.getElementById("box");
var speed = 0;
document.onclick = function () {
move(oBox, 300)
};
function move(obj, iTarget) {
setInterval(function () {
speed += (iTarget - obj.offsetLeft) / 2;
//摩擦力
speed *= 0.8;
oBox.style.left = oBox.offsetLeft + speed + 'px';
}, 30)
}
碰撞运动
var timer = null;
var oBox = document.getElementById("box");
var disX = 10;
var disY = 8;
var iw = document.documentElement.clientWidth - oBox.offsetWidth;
var ih = document.documentElement.clientHeight - oBox.offsetHeight;
document.onclick = function () {
timer = setInterval(function () {
disY += 5;
var l = oBox.offsetLeft + disX;
var t = oBox.offsetTop + disY;
if (l >= iw) {
disX *= -0.8;
l = iw;
}
if (l <= 0) {
disX *= -0.8;
l = 0;
}
if (t >= ih) {
disY *= -0.8;
disX *= 0.8;
t = ih;
}
if (t <= 0) {
disY *= -0.8;
disX *= 0.8;
t = 0;
}
if (Math.abs(disX) <= 1) {
disX = 0;
}
//纯属碰巧
if (Math.abs(disY) <= 2) {
disY = 0;
}
if (disX == 0 && disY == 0) {
clearInterval(timer);
}
console.log(disY, disX)
oBox.style.left = l + 'px';
oBox.style.top = t + 'px';
}, 30)
}