0
点赞
收藏
分享

微信扫一扫

原生JS实现各种运动之链式运动


给大家分享一个用原生JS实现的链式运动,所谓链式运动即为一个属性变化完成后另一个属性接着发生变化,效果如下:

原生JS实现各种运动之链式运动_JavaScript

 实现代码如下,欢迎大家复制粘贴及吐槽。 

<!DOCTYPE html>
<html>

<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>原生JS实现各种运动之链式运动</title>
<style>
#box {
width: 100px;
height: 100px;
background: red;
opacity: 0.3;
}
</style>

</head>

<body>
<div id="box"></div>

<script>
// 获取属性值
function getStyle(obj, attr) {
// 用两种不同的情况处理兼容
if (obj.currentStyle) {
return obj.currentStyle[attr];
} else {
return getComputedStyle(obj, false)[attr];
}
}
// 运动方法,callback为回调函数,实现链式调用
function startMove(obj, attr, target, callback) {
// 防止连续点击出现多个定时器
clearInterval(obj.timer);
// 为当前对象添加定时器
obj.timer = setInterval(function () {

var current = 0;
// 如果获取的属性值为透明度
if (attr == 'opacity') {
// 获取透明度值
current = parseInt(parseFloat(getStyle(obj, attr)) * 100);

} else {
// 获取其它属性值
current = parseInt(getStyle(obj, attr));
}

// 实现缓冲运动
var speed = (target - current) / 8;
// 将值取整,以免永远无法达到目标值
speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed);

// 如果已经达到目标值
if (current == target) {
// 清除定时器
clearInterval(obj.timer);

// 判断是否存在,以免最后一个回调函数报错
if (callback) {
callback();
}
// 否则
} else {
// 如果属性为透明度
if (attr == 'opacity') {
// 为透明度赋值,分别处理兼容
obj.style.filter = 'alpha(opacity:' + (current + speed) + ')';
obj.style.opacity = (current + speed) / 100;
} else {
// 设置其它属性的值
obj.style[attr] = current + speed + 'px';
}
}
}, 30)
}
</script>
<script>

window.onload = function () {
var box = document.getElementById('box');
box.onmouseover = function () {
startMove(box, 'width', 300, function () {
startMove(box, 'height', 300, function () {
startMove(box, 'opacity', 100);
});
});
};
box.onmouseout = function () {
startMove(box, 'opacity', 30, function () {
startMove(box, 'height', 100, function () {
startMove(box, 'width', 100);
});
});
};
};

</script>
</body>

</html>

举报

相关推荐

0 条评论