封装好的动画函数:
// 封装好的动画函数,可以直接调用
//1.让盒子每次移动的距离慢慢变小,速度就会慢慢落下来
//2.核心算法:(目标值-现在的位置)/10 做为每次移动的距离 步长
//3.停止的条件:让当前盒子位置等于目标位置就停止定时器
function animate(obj,target,callback){ //obj目标对象 target目标位置 callback()回调函数
//先清除以前的定时器,只保留当前的一个定时器执行
clearInterval(obj.timer);
obj.timer=setInterval(function(){
//步长值写到定时器的里面
//把步长值改为整数,不要出现小数的问题
var step=(target-obj.offsetLeft)/10;
step=step>0 ? Math.ceil(step) :Math.floor(step);
if(obj.offsetLeft==target){
//停止动画,本质是停止定时器
clearInterval(obj.timer);
//回调函数写到定时器结束里面
if(callback){
//调用函数
callback();
}
}
//把每次加1这个步长值改为一个慢慢变小的值,步长公式:(目标值-现在的位置)/10
obj.style.left=obj.offsetLeft+step+'px';
},15);
}
setInterval()定时器
window.setInterval(回调函数,间隔的毫秒数);
该方法重复调用一个函数,每隔一段时间就去调用一次回调函数,并且这个定时器一旦开启,永不停歇。
调用动画函数示例
<!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>Document</title>
<style>
.sliderbar {
position: fixed;
right: 0;
bottom: 100px;
width: 40px;
height: 40px;
text-align: center;
line-height: 40px;
cursor: pointer;
color: #fff;
}
.con {
position: absolute;
left: 0;
top: 0;
width: 200px;
height: 40px;
background-color: purple;
z-index: -1;
}
</style>
<script src="cartoon.js"></script>
</head>
<body>
<div class="sliderbar">
<span> <- </span>
<div class="con">问题反馈</div>
</div>
<script>
//1.获取元素
var sliderbar=document.querySelector('.sliderbar');
var con =document.querySelector('.con');
//当我们鼠标经过sliderbar就会让con这个盒子滑动到左侧
//当我们鼠标离开sliderbar就会让con这个盒子滑动到右侧
sliderbar.addEventListener('mouseenter',function(){
animate(con,-160,function(){
//当我们动画执行完毕,就把<-改为->
sliderbar.children[0].innerHTML='->';
});
})
sliderbar.addEventListener('mouseleave',function(){
animate(con,0,function(){
sliderbar.children[0].innerHTML='<-';
});
})
</script>
</body>
</html>