#缓慢动画
<style>
.box{
width: 100px;
height: 100px;
position: relative;
background: red;
}
</style>
<div class="box"></div>
<script>
var box = document.querySelector(".box")
// function animate(obj,target){
// var left = 0;
// var timer = setInterval(function(){
// left += 10
// if(left >= target){
// clearInterval(timer)
// }
// obj.style.left = left + "px"
// },30)
// }
function animate(obj,target){
clearInterval(obj.timer)
obj.timer = setInterval(function(){
var step = (target - obj.offsetLeft) / 10
if(obj.offsetLeft == target){
clearInterval(obj.timer)
}
obj.style.left = obj.offsetLeft + step + "px"
},30)
}
animate(box,500)
</script>
#步长优化
<style>
.box{
width: 100px;
height: 100px;
position: relative;
background: red;
}
</style>
<div class="box"></div>
<script>
var box = document.querySelector(".box")
function animate(obj,target){
clearInterval(obj.timer)
obj.timer = setInterval(function(){
var step = (target - obj.offsetLeft) / 10
step = step > 0 ? Math.ceil(step): Math.floor(step)
console.log(step)
if(obj.offsetLeft == target){
clearInterval(obj.timer)
}
obj.style.left = obj.offsetLeft + step + "px"
},30)
}
animate(box,500)
</script>
#回调函数
<script>
// 回调函数,回头再调用的函数
// var btn =
// // 这个函数就是回调函数!!!
// btn.onclick = function() {
// }
// fn想当于function() {
// console.log("这个函数是一个回调函数, 2s后进行回调")
// }
function demo(fn) {
setTimeout(function() {
fn()
}, 2000)
}
demo(function() {
console.log("这个函数是一个回调函数, 2s后进行回调")
})
</script>
#缓慢动画加上回调函数
<style>
.box{
width: 100px;
height: 100px;
position: relative;
background: red;
}
</style>
<div class="box"></div>
<script>
var box = document.querySelector(".box")
function animate(obj,target,fn){
clearInterval(obj.timer)
var header = 0
obj.timer = setInterval(function(){
var step = (target - header) / 10
step = step > 0 ? Math.ceil(step): Math.floor(step)
header = header + step
console.log(header)
console.log(target)
if(header == target){
clearInterval(obj.timer)
if(fn){
fn()
}
}
obj.style.left = obj.offsetLeft + step + "px"
},30)
}
animate(box,500,function(){
box.style.background = "pink"
})
</script>