动画函数

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,height=device-height,initial-scale=1.0,maximum-scale=1.0,minimum-scale=1.0,user-scalable=no,viewport-fit=cover">
<title>动画函数</title>
<style>
* {
margin: 0;
padding: 0;
}
#box {
width: 100px;
height: 100px;
background: red;
position: absolute;
top: 60px;
left: 0;
}
</style>
</head>
<body>
<button id="btn1">滑动到400px</button>
<button id="btn2">滑动到800px</button>
<div id="box"></div>
<script>
var btn1 = document.querySelector('#btn1');
var btn2 = document.querySelector('#btn2');
var box = document.querySelector('#box');

btn1.addEventListener('click', function () {
animate(box, 400);
});
btn2.addEventListener('click', function () {
animate(box, 800);
});

//封装动画函数
function animate(obj, target) {
clearInterval(obj.timerId);
obj.timerId = setInterval(function () {
var step = 9;
var current = obj.offsetLeft;
step = current < target ? step : -step;
current = current + step;
if (Math.abs(target - current) > Math.abs(step)) {
obj.style.left = current + 'px';
}else {
obj.style.left = target + 'px';
clearInterval(obj.timerId);
}
}, 30)
}
</script>
</body>
</html>
posted @ 2019-12-02 08:33  詹姆斯小皇帝  阅读(135)  评论(0编辑  收藏  举报