js之多属性运动函数封装
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style>
div {
width: 300px;
height: 300px;
background-color: red;
}
</style>
<script type="text/javascript">
window.onload = function() {
var oDiv = document.querySelector('div');
oDiv.onclick = function() {
bufferMove(this, {width: 500,height: 500,opacity: 50},function(){alert('动画执行完毕')}) //opacity由于在函数中起点值扩大了100倍,因此在传入终点值的时候也要对应扩大100倍
//300---500 100---50
}
function bufferMove(ele, json, fun) {
//json接收的对象形式: {添加动画的属性名:终点值}
//fun用来接收回调函数
//清除定时器
clearInterval(ele.timer);
ele.timer = setInterval(function() {
//设置标识 判断是否都执行完
var flag = true; //true表示都执行完
//循环json对象
for (key in json) {
var attr = key;
var target = json[key];
//起点
if (attr == 'opacity') {
var cur = getStyle(ele, attr) * 100;
} else {
var cur = parseInt(getStyle(ele, attr));
}
//步长
var step = (target - cur) / 10;
// 如果步长大于0 要向上取整, 步长小于0 要向下取整
step = step > 0 ? Math.ceil(step) : Math.floor(step);
cur += step;
//判断是否都执行完毕
if (step > 0 && cur < target) {
flag = false; //没有执行完
} else if (step < 0 && cur > target) {
flag = false;
}
//判断终点
// if (step > 0 && cur >= target) {
// clearInterval(ele.timer);
// cur = target;
// } else if (step < 0 && cur <= target) {
// clearInterval(ele.timer);
// cur = target;
// }
//设置
if (attr == 'opacity') {
ele.style[attr] = cur / 100;
} else {
ele.style[attr] = cur + 'px';
}
}
if (flag == true) {
//清除定时器
clearInterval(ele.timer);
//执行完毕提示
if(fun){
fun();
}
}
}, 20)
}
function getStyle(ele, attr) {
if (ele.currentStyle == undefined) {
return getComputedStyle(ele)[attr];
} else {
return ele.currentStyle[attr];
}
}
}
</script>
</head>
<body>
<div></div>
</body>
</html>
本文来自博客园,作者:JackieDYH,转载请注明原文链接:https://www.cnblogs.com/JackieDYH/p/17634771.html