var div = document.querySelector("div")
var but500 = document.querySelector('.but500')
var but800 = document.querySelector('.but800')
function main(obj, timer , fun) {
//有按钮时,按按钮会给盒子叠加定时器
//根据代码从上向下执行的规定,先写一个clearInterval清除上一定时器,让定时器保持一个的数量
clearInterval(obj.a)
obj.a = setInterval(function () {
//盒子既能前进也能后退,不同条件取值条件也不同
var step = (timer - obj.offsetLeft) / 10
//盒子前进为正值时向上取整,为负时向下取整
step = step > 0 ? Math.ceil(step) : Math.floor(step)
if (obj.offsetLeft === timer) {
clearInterval(obj.a)
if (fun) {
fun();
}
}
obj.style.left = obj.offsetLeft + step + 'px'
}, 15)
}
but500.addEventListener('click', function () {
main(div, 500 , function () {
div.style.backgroundColor = 'red'
})
})
but800.addEventListener('click', function () {
main(div, 800 , function () {
div.style.backgroundColor = 'pink'
})
})
黑马js封装简单动画函数案例
于 2022-06-03 09:34:34 首次发布