样式
<style>
.box {
position: fixed;
width: 100px;
height: 100px;
background-color: pink;
left: 0;
top: 0;
}
</style>
js
<body>
<div class="box"></div>
<script>
// ele表示DOM,target表示目标位置
function move(ele, target) {
typeof ele === 'string' && (ele = document.querySelector(ele))
let left = ele.offsetLeft;
// 用定时器实现动画效果
let t = setInterval(function() {
left += 10;
if (left >= target) {
left = target;
ele.style.left = left + 'px';
// 到达指定位置,清除定时器
clearInterval(t)
}
ele.style.left = left + 'px';
}, 1000 / 60)
}
// 调用函数
move('.box', 500)
</script>
</body>