原生 JavaScript 模仿j Query 缓动动画
注:适用于各种数值或数值字符串的属性(opacity除外)
HTML部分
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document测试2</title>
<style>
#box {
width: 100px;
height: 100px;
background-color: red;
}
</style>
</head>
<body>
<div id="box"></div>
<script src="./animate.js"></script>
<script>
$("#box").animate({
width: 1000,
height: 200,
marginLeft: '100px'
}, 100)
</script>
</body>
</html>
animate函数封装
; (function () {
// .0 分析原理
// 目标属性 = 当前属性值+步长
// 步长=(目标属性值-当前属性值)/数字 【控制速度】
// 1.0 定义函数 $
var $ = function (selector) {
window['element'] = document.querySelector(selector);
return window;
};
// 2.0 在window下 添加方法
window.animate = function (option, seconds) {
// .0 清除定时器
clearInterval(window.element.timer);
// .0 执行定时器
window.element.timer = setInterval(function () {
var bool = true;
// 循环对象
for (var propety in option) {
// 目标值
var targetValue = parseInt(option[propety]);
// 当前值
// getComputedStyle()
var currenValue = getComputedStyle(window.element)[propety];
currenValue = parseInt(currenValue); //去除px
// 计算步长
var speed = (targetValue - currenValue) / 10;
// 处理小数点
speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed);
// 判断 如果有一个属性未达到目标值
if (currenValue != targetValue) {
bool = false;
}
// 设置元素属性
window.element.style[propety] = currenValue + speed + 'px';
}
// 如果到达目标值 则所有属性都达到目标值
if (bool) {
// 清除定时器
clearInterval(window.element.timer);
// 执行回调函数
// if(typeof option){}
}
}, seconds)
}
// 把$挂载到全局对象下
window.$ = $;
})()