思路
1.首先缓动动画函数封装 ,obj目标对象 ,target目标位置,这样可以不用每次要使用动画效果的时候都写一次js代码,
2.让盒子每次移动的距离慢慢变小,速度就会慢慢落下来
3.核心算法:(目标值-现在的位置)/10作为每次移动得距离 步长(这里步长要取整)
4.停止条件:让当前盒子位置等于目标位置就停止定时器
js代码如下
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);
if(obj.offsetLeft == target){
// 停止动画,也就是停止定时器
clearInterval(obj.timer);
obj.style.left = obj.offsetLeft + step + 'px';
},30);
}然后调用这个函数实现缓动动画效果,
<!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>缓动动画</title>
<script src="javasc.js"></script>
<style>
div{
position: absolute;
left: 0;
height: 100px;
width: 100px;
background-color: red;
margin-top: 20px;
}
</style>
</head>
<body>
<button class="btn500">点击我移动500</button>
<button class="btn800">点我移动800</button>
<div class="dd"></div>
<script>
var btn = document.querySelector('.btn500');
var btn1 = document.querySelector('.btn800');
var di = document.querySelector('.dd');
btn.addEventListener('click',function(){
animate(di,500)
});
btn1.addEventListener('click',function(){
animate(di,800)
})
</script>
</body>
</html>在缓动动画上还可以添加回调函数,当定时器执行完成后,再调用callback函数
首先写一个盒子,当动画执行完成之后,盒子里面的内容就改变
代码如下
<!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{
width: 30px;
height: 30px;
}
span{
display: inline-block;
position: absolute;
left: 0;
width: 30px;
height: 30px;
line-height: 30px;
background-color:rgb(78, 226, 115);
z-index: 999;
}
.con{
position: absolute;
left: -70px;
width: 100px;
height: 30px;
line-height: 30px;
background-color: pink;
z-index: -1;
text-align: center;
}
</style>
</head>
<body>
<div class="sliderbar">
<span>→</span>
<div class="con">我出现啦</div>
</div>
<script>
var sliderbar = document.querySelector('.sliderbar');
var con = document.querySelector('.con');
var span = document.querySelector('span');
function animate(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();
}
}
obj.style.left = obj.offsetLeft + step + 'px';
},30);
}
sliderbar.addEventListener('mouseenter',function(){
animate(con,30,function(){
span.innerHTML = '←';
});
})
sliderbar.addEventListener('mouseleave',function(){
animate(con,-70,function(){
span.innerHTML = '→';
});
})
</script>
</body>
</html>版权声明:本文为weixin_53849180原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。