<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
.box {
position: absolute;
top: 50px;
left: 0;
width: 105px;
height: 105px;
padding: 5px;
background: pink;
}
.box1,
.box2,
.box3,
.box4 {
float: left;
width: 50px;
height: 50px;
border: 1px solid black;
}
.box1 {
background: rgb(239, 163, 163);
}
.box2 {
background: rgb(186, 247, 155);
}
.box3 {
background: rgb(155, 233, 247);
}
.box4 {
background: rgb(155, 155, 247);
}
</style>
</head>
<body>
<button>移动到1000</button>
<button>移动到500</button>
<div class="box">
<div class="box1"></div>
<div class="box2"></div>
<div class="box3"></div>
<div class="box4"></div>
</div>
<script>
// 获取页面元素
var box = document.querySelector('.box');
var btn = document.querySelectorAll('button');
btn[0].onclick = function () {
fn(box, 1000)
}
btn[1].onclick = function () {
fn(box, 500, function () {
box.style.backgroundColor = 'yellow'
box.style.padding = 20 + 'px';
})
}
function fn(ele, target, callback) {
// 清除上一次的定时器
clearInterval(ele.timer)
// 定时器
ele.timer = setInterval(function () {
// 计算步长
var step = (target - box.offsetLeft) / 10;
// 取正(向下/向上)
step = step > 0 ? Math.ceil(step) : Math.floor(step);
if (box.offsetLeft == target) {
clearInterval(ele.timer);
// 回调函数
if (callback) {
callback()
}
callback && callback()
}
box.style.left = box.offsetLeft + step + 'px';
}, 50)
}
</script>
</body>
</html>
缓动动画(速度由快转慢)
最新推荐文章于 2024-10-18 17:51:23 发布