给大家分享一个用原生JS实现的复合运动,所谓复合运动就是在同一个进间段内不同的属性都会发生变化,效果如下:
实现代码如下,欢迎大家复制粘贴及吐槽。
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>原生JS实现各种运动之复合运动</title>
<style>
#obj {
width: 100px;
height: 100px;
background: red;
opacity: 0.3;
}
</style>
</head>
<body style="background:#0F0;">
<input id="button" type="button" value="开始运动" />
<div id="obj"></div>
<script>
window.onload = function () {
var button = document.getElementById('button');
var obj = document.getElementById('obj');
button.onclick = function () {
startMove(obj, {
width: 400,
height: 200,
opacity: 100
});
};
};
function getStyle(obj, attr) {
if (obj.currentStyle) {
return obj.currentStyle[attr];
} else {
return getComputedStyle(obj, false)[attr];
}
}
function startMove(obj, json, callback) {
clearInterval(obj.timer);
obj.timer = setInterval(function () {
// 设定开关,防止某一个值达到后其它值停止变化
var stop = true;
for (var attr in json) {
var current = 0;
if (attr == 'opacity') {
current = parseInt(parseFloat(getStyle(obj, attr)) * 100);
} else {
current = parseInt(getStyle(obj, attr));
};
var speed = (json[attr] - current) / 8;
speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed);
// 如果某一个值还没有达到
if (current != json[attr]) {
stop = false;
};
if (attr == 'opacity') {
obj.style.filter = 'alpha(opacity:' + (current + speed) + ')';
obj.style.opacity = (current + speed) / 100;
} else {
obj.style[attr] = current + speed + 'px';
}
}
// 最后一轮循环时清除定时器
if (stop) {
clearInterval(obj.timer);
if (callback) {
callback();
}
}
}, 30)
}
</script>
</body>
</html>