1 JS动画实现原理
原理:通过定时器不断地改变目标位置
例子:
让div运动到500px的时候停下
<style>
* {
padding: 0;
margin: 0;
}
.box {
width: 200px;
height: 200px;
background-color: pink;
position: absolute;
left: 0;
top: 0;
}
</style>
// 让div运动到500px停下
var box = document.querySelector('.box');
//console.log(box.offsetLeft);
// 运动核心就是 不断调整位置
var timer = setInterval(function() {
if (box.offsetLeft >= 500) {
//return 用户停止函数执行
return clearInterval(timer);
}
box.style.left = box.offsetLeft + 1 + 'px';
},30);
运动函数简易封装
<style>
* {
padding: 0;
margin: 0;
}
.box {
width: 200px;
height: 200px;
background-color: pink;
position: absolute;
left: 0;
top: 0;
}
p.box {
top: 220px;
}
</style>
</head>
<body>
<div class="box"></div>
<p class="box"></p>
<button id="btn">让p跑起来</button>
<script>
// 让div运动到500px停下
var box = document.querySelector(".box");
var oP = document.querySelector('p');
var btn = document.querySelector('#btn');
//console.log(box.offsetLeft);
animate(box,500);
btn.addEventListener('click',function() {
animate(oP,200);
});
//封装函数animate()
function animate(obj, target) {
// 确保元素只有一个定时器执行
clearInterval(obj.timer);
// 运动核心就是 不断调整位置
obj.timer = setInterval(function() {
if (obj.offsetLeft >= target) {
return clearInterval(obj.timer);
}
obj.style.left = obj.offsetLeft + 1 + "px";
}, 30);
}
</script>
</body>
2 缓动动画
匀速运动:给予定时间内一个运动的常值,盒子当前位置+固定值
缓动动画:给予定时间内运动的一个变化的值,盒子当前位置+ 变化值 比如 (目标值-当前位置)/ 10
function animate(obj, target) {
// 确保元素只有一个定时器执行
clearInterval(obj.timer);
// 运动核心就是 不断调整位置
obj.timer = setInterval(function() {
//变化值
var step = (target - obj.offsetLeft) / 10;
if (obj.offsetLeft >= target) {
return clearInterval(obj.timer);
}
obj.style.left = obj.offsetLeft + step + "px";
}, 30);
}
3 函数封装
//元素移动函数
function animate(obj, json, callback) {
// 确保元素只有一个定时器执行
clearInterval(obj.timer);
// 运动核心就是 不断调整位置
obj.timer = setInterval(function() {
var current;
for (var attr in json) {
if (attr === "opacity") {
current = parseFloat(getStyle(obj, "opacity")) * 100;
} else if (attr === 'zIndex') {
current = parseInt(getStyle(obj, attr));
} else {
current = parseInt(getStyle(obj, attr));
}
var step = (json[attr] - current) / 10;
step = step > 0 ? Math.ceil(step) : Math.floor(step);
if (Math.round(current) == json[attr]) {
clearInterval(obj.timer);
//如果有回调函数,则执行函数,然后返回
if (callback) {
callback();
return;
}
}
if (attr === "opacity") {
obj.style[attr] = (current + step) / 100;
} else if (attr === 'zIndex') {
obj.style[attr] = current + step;
} else {
obj.style[attr] = current + step + "px";
}
}
}, 30);
}
// 获取元素最终样式
function getStyle(obj, attr) {
if (window.getComputedStyle) {
return window.getComputedStyle(obj, false)[attr];
} else {
return obj.currentStyle[attr];
}
}