利用JS实现一个盒子的减速滑动
<!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;
}
div {
width: 100px;
height: 100px;
background-color: pink;
position: absolute;
left: 0;
}
span {
width: 300px;
height: 300px;
background-color: green;
position: absolute;
top: 500px;
left: 0;
}
</style>
</head>
<body>
<button>点击</button>
<div></div>
<span></span>
<script>
var button = document.querySelector('button');
var div = document.querySelector('div');
var span = document.querySelector('span');
function ainimate(obj, target) {
clearInterval(obj.timer)
obj.timer = setInterval(function () {
//步长值
var h = (target - obj.offsetLeft) / 10;
if (obj.offsetLeft >= target) {
clearInterval(obj.timer);
} else {
//把加一改成每次都变化的步长值
obj.style.left = (obj.offsetLeft + h) + 'px';
}
}, 30)
}
ainimate(div, 900);
button.addEventListener('click', function () {
ainimate(span, 400);
})
</script>
</body>
</html>