以后经常使用这个函数的话,可以单独封装到一个Js文件,使用时引用即可。
1.单独新建一个js文件
2.直接引用
<script type="text/javascript" src="animate.js"></script>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
.sliderbar {
position: fixed;
right: 0;
bottom: 100px;
width: 40px;
height: 40px;
line-height: 40px;
text-align: center;
color: #fff;
cursor: pointer;
background-color: skyblue;
}
.con {
position: absolute;
left: 0;
top: 0;
width: 200px;
height: 40px;
background-color: skyblue;
z-index: -1; /* 这里设置为-1的原因就是让箭头压在con的上边 否则con移动过去之后会压住箭头 箭头就看不到了 */
}
</style>
</head>
<body>
<div class="sliderbar">
<span>←</span>
<div class="con">问题反馈</div>
</div>
<script type="text/javascript">
var sliderbar = document.querySelector('.sliderbar');
var con = document.querySelector('.con');
var span = document.querySelector('span');
//鼠标经过sliderbar 就会让con这个盒子滑动到左侧
//鼠标离开sliderbar 就会让con这个盒子滑动到右侧
sliderbar.addEventListener('mouseenter', function() {
animate(con, -160, function() {
span.innerHTML = '→';
});
});
sliderbar.addEventListener('mouseleave', function() {
animate(con, 0, function() {
span.innerHTML = '←';
});
})
</script>
</body>
</html>
animate.js:
function animate(obj, target,callback) {
// console.log(callback); //callback = function() {}
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';
},15);
}