封装一个运动函数
获取元素:var oDiv = document.querySelector('div')
- 封装一个运动函数,方便多次调用,减少代码量
function move(ele,options,callback) {
//创建一个变量为计数器
let count = 0
for(let key in options){
//获取属性以及属性值
let type = key
let target = options[key]
count++
//1.开启定时器
const timer = setInterval (() => {
//2.获取当前位置
let init = parseInt(window.getComputedStyle(ele)[type])
//3.计算本次移动距离 (目标 - 当前值)/10
let duration = (target - init) / 10
//4.判断移动距离是否大于0,从而采取取整方式
duration = duration > 0 ? Math.ceil(duration) : Math.floor(duration)
//5.判断走不走
if(init === target){
clearInterval(timer)
count--
if(count === 0) {
callback()
}
} else {
//元素原本位置 + 移动的距离 赋值给元素
ele.style[type] = init + duration + 'px'
}
},20)
}
}
//绑定点击事件
oDiv.onclick = function () {
move(this,{
width:200,
height:350,
top:100,
left:250
},()=>{
this.style.backgroundColor = 'pink'
})
}
总结:封装函数,方便多次调用,减少代码量