//简单动画函数封装 obj目标对象 target目标位置//给不同的元素指定了不同的定时器//缓动动画function animate (obj,target,callback) {clearInterval(obj.timer);//让盒子在当前位置+1距离//定时器重复操作,最后清除定时器obj.timer = setInterval(function(){//步长值写到定时器的里面var step = (target - obj.offsetLeft) / 10;step = step > 0 ? Math.ceil(step) : Math.floor(step);//获得盒子当前的位置var x = obj.offsetLeft;if(x == target){clearInterval(obj.timer);//回调函数写在定时器结束的位置if(callback){//调用函数callback();}}obj.style.left = x + step + 'px';},15);}
<!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="./animate.js"></script><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></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');sliderbar.addEventListener('mouseenter',function(){animate(con,-160,function(){span.innerHTML = '➡';});});sliderbar.addEventListener('mouseleave',function(){animate(con,0,function(){span.innerHTML = '⬅';});});</script></body></html>
.
