<!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>
* {
padding: 0;
margin: 0;
}
.box {
width: 100px;
height: 100px;
background-color: pink;
position: absolute;
top: 0;
left: 100px;
opacity: 0.1;
}
</style>
</head>
<body>
<div class="box"></div>
<script>
function move(el, options, callback) {
let num = 0
for (let key in options) {
num++
const type = key
let target = options[key]
if(type === "opacity") target *= 100
const timer = setInterval(() => {
let count = type === "opacity" ? window:getComputerStyle(el)[type] * 100 : paeseInt(window.getComputedStyle(el)[type])
let duration = (target - count) / 10
duration = duration > 0 ? Math.ceil
(duration) : Math.floor(duration)
if(target === count){
clearInterval(timer)
每关闭一次定时器,就对我们的计数器--,如果有一次--完毕,计数器的值===初始值,就证明此刻是运动函数真正结束的时候
num--
if(num === 0) {
callback()
}
} else {
el.style[type] = type === "opcity" ? count / 100 + duration / 100 : count + duration + "px"
}
},20)
}
}
box.onclick = function () {
move(
box,
{
opacity: 1,
left: 200,
top: 200,
width: 400
},
() => {box.style.backgroundColor = "green"}
)
}