<style>
.box {
width: 100px;
height: 100px;
background-color: red;
position: absolute;
left: 0px;
top: 0px;
}
</style>
<div class="box"></div>
<script>
var box = document.querySelector(".box");
function move(ele, target, dis) {
return new Promise((resolve, reject) => {
function fn() {
let direction = parseInt(getComputedStyle(ele)[dis]);
let speed = 1 * (target - direction) / Math.abs(target - direction);
setTimeout(() => {
direction += speed;
if (target === direction) {
resolve();
} else {
ele.style[dis] = direction + "px";
fn();
}
})
}
fn();
})
}
async function fn() {
try {
await move(box, 300, "left");
console.log("第一圈完成");
await move(box, 300, "top");
console.log("第二圈完成");
await move(box, 0, "left");
console.log("第三圈完成");
await move(box, 0, "top");
console.log("回到原点了哥");
} catch (e) {
console.log(e);
}
}
fn();