封装一个运动函数,方便后期使用,减少代码量
// 获取元素
const box = document.querySelector('.box')
绑定点击事件
box.onclick = function () {
// 调用运动函数
// 改变多个属性时,需要调用多次 move 函数,就可以使用回调函数
move(this,{
width: 500,
height: 500,
top: 200,
left: 200
},() => {
this.style.backgroungColor = 'red'
})
}
封装函数
function move (ele,obj,fn) {
// 定义一个计数器,用来判断程序什么时候运行结束
let count = 0
// 遍历对象,取值
for(let key in obj) {
let type = key
let target = obj[key]
// 每进行一次,就给计数器++
count++
// 设置一个计时器
var timer = setInterval( () => {
// 1: 获取元素的位置
// window.getComputedStyle(元素) 获取元素属性,得到的是字符串形式的,所以要parseInt转换一下
let init = parseInt(window.getComputedStyle(ele)[type])
// 2: 计算元素的移动距离 (目标距离 - 元素本身位置) / 10
// 这里 / 10 是为了缓慢移动,而不是一下子到了指定位置
let duration = (target - init) / 10
// 3: 判断移动距离 如果小于0,那么向下取整,大于0向上取整
duration = duration > 1 ? Math.ceil(duration) : Math.floor(duration)
// 4: 判断还要不要继续移动
if(init == target) {
clearInterval(timer)
// 这里是结束运行完毕
count--
if(count === 0){
console.log('程序执行完毕')
}
// 调用函数,执行代码改变颜色
fn()
} else {
// 元素原本的位置 + 要移动的距离, 赋值给元素
ele.style[type] = init + duration + 'px'
}
},20)
}
}