效果图
结构
<div class="sliderbar">
<span>--</span>
<div class="con">问题反馈</div>
</div>
<script src="animate.js"></script>
CSS
.sliderbar {
position: absolute;
right: 100px;
top: 15px;
}
span {
position: absolute;
left: 0;
top: 0;
width: 40px;
height: 40px;
background-color: red;
}
.con {
position: absolute;
left: 0;
top: 0;
width: 200px;
height: 40px;
background-color: purple;
z-index: -1;
}
js
//获取元素
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 = '';
});
})
animate.js
function animate(obj, target, callback) {
// console.log(callback); callback = function () { } 调用的时候callback()
// 先清除以前的定时器 只保留当前的一个定时器执行
clearInterval(obj.timer);
obj.timer = setInterval(function () {
// 步长值写到定时器里面
// 把我们步长值改为证书 不要出现小数的问题
// var step = Math.ceil((target - obj.offsetLeft) / 10);
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);
}