-
实现效果
-
实现代码
动画函数封装了起来,并且单独写在js文件中,需要引用
function animate(obj, target, callback) {
clearInterval(obj.timer);
obj.timer = setInterval(function () {
var moveDistance = (target - obj.offsetLeft) / 10;
var step = Math.ceil(moveDistance);
console.log(obj.offsetLeft);
console.log(target);
if (obj.offsetLeft == target) {
clearInterval(obj.timer);
// 回调函数写在定时器结束的条件里面
if (callback) {
callback();
}
}
obj.style.left = obj.offsetLeft + 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>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>
<!-- 引入js文件 -->
<script src="animate.js"></script>
</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>