<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.box {
100px;
height: 100px;
position: absolute;
background-color: #ccc;
}
</style>
</head>
<body>
<div class="box"></div>
<script>
var box = document.querySelector(".box")
function animate(obj, target, callback) {
clearInterval(obj.timer)
obj.timer = setInterval(() => {
var step = (target - obj.offsetLeft) / 10
step = step > 0 ? Math.ceil(step) : Math.floor(step)
if (obj.offsetLeft === target) {
clearInterval(obj.timer)
if (callback) {
callback()
}
}
console.log(obj.offsetLeft)
obj.style.left = obj.offsetLeft + step + 'px'
}, 40)
}
animate(box, 1000)
</script>
</body>
</html>