<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>平移动画</title>
<style>
* {
margin: 0;
padding: 0;
}
.box {
width: 100px;
height: 80px;
background-color: aqua;
position: absolute;;
}
</style>
</head>
<body>
<button class="btn1">平移400</button>
<button class="btn2">平移800</button>
<div class="box"></div>
<script>
var btn1 = document.querySelector('.btn1');
var btn2 = document.querySelector('.btn2');
var box = document.querySelector('.box');
// box.offsetLeft = 400;
console.log(box.offsetLeft);
btn1.onclick = function() {
var timer = setInterval(function() {
// 获取box起始位置
var current = box.offsetLeft;
// 规定单位时间内移动的距离. 平均速度 10px/20ms
var step = 10;
if(current < 400) {
box.style.left = current + step + 'px';
} else {
clearInterval(timer);
}
}, 20);
}
btn2.onclick = function() {
var timer = setInterval(function() {
// 获取box起始位置
var current = box.offsetLeft;
// 规定单位时间内移动的距离. 平均速度 10px/20ms
var step = 10;
if(current < 800) {
box.style.left = current + step + 'px';
} else {
clearInterval(timer);
}
}, 20);
}
</script>
</body>
</html>
上述运行结果: