<!DOCTYPE html>
<!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>运动函数</title>
<style>
*{padding: 0; margin: 0;}
.box{
width: 200px;
height: 200px;
background-color: aqua;
position: absolute;
top: 100px;
left: 200px;
}
</style>
</head>
<body>
<div class="box"></div>
<script>
/*
移动到501 不为5的倍数
如何解决
1.每次移动1
2.每次移动距离的十分之一
3.
*/
//回调函数
//把函数a 以实参的形式传递到函数 b内部
//在函数b 内部,以形参的方式调用函数 a
//此时我们可以把函数a 叫做函数b的回调函数
const oBox = document.querySelector('.box')
oBox.onclick = function(){
move(oBox,{
left:400,
top: 500,
width:500,
height:600
},function(){
oBox.style.backgroundColor = 'red'
})
}
function move(ele,json,call1){
//得到的是带px的字符串 需要用parseInt
let count = 0
for(let key in json){
let type = key
let target = json[key]
//因为定时器 异步 所以是结束后 定时器再执行4次
count++
console.log(1)
const timer = setInterval(()=>{
//2.获取当前位置
let int =parseInt(window.getComputedStyle(ele)[type])
//3.计算本次移动距离
// console.log(int)
//每次都用剩余的/10
let duration = (target - int) / 10
//判断最后的小数 -数的时候-0.9 向下取整-1
if(duration > 0){
duration = Math.ceil(duration)
}else{
duration = Math.floor(duration)
}
// console.log(duration)
//4.判断走还是不走
if(target === int){
console.log('我')
clearInterval(timer)
count--
if(count === 0){
console.log('结束了')
call1 && call1()
}
}else{
ele.style[type] = int + duration + 'px'
}
},1000/60)
}
}
</script>
</body>
</html>