<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
* {
padding: 0;
margin: 0;
}
.box {
width: 200px;
height: 200px;
background-color: aquamarine;
position: absolute;
top: 0px;
left: 0px;
}
</style>
</head>
<body>
<div class="box"></div>
<script>
var box = document.querySelector('.box')
box.onclick = function() {
move(this, {
left: 100,
top: 100,
width:400,
height:300
}, () => {
box.style.backgroundColor = 'red'
})
}
function move (ele, options ,fn) {
let count = 0
for(let key in options) {
let type = key
let target = options[key]
count++
const timer = setInterval(() => {
let init = parseInt(window.getComputedStyle(ele)[type])
let duration = (target - init) / 10
duration = duration > 0 ? Math.ceil(duration) : Math.floor(duration)
if(target === init) {
clearInterval(timer)
count--
if(count === 0) {
fn()
}
} else {
ele.style[type] = init + duration + 'px'
}
}, 20)
}
}
</script>
</body>
</html>