.sliderbar { width: 200px; height: 40px; position: relative; margin: 0 auto; } .sliderbar span { display: inline-block; width: 50px; text-align: center; line-height: 40px; background-color: pink; } .con { display: inline-block; position: absolute; width: 150px; text-align: center; line-height: 40px; background-color: pink; }
<div class="sliderbar"> <span>←</span> <div class="con">问题反馈</div> </div>
var sliderbar = document.querySelector(‘.sliderbar‘) var con = document.querySelector(‘.con‘) sliderbar.addEventListener(‘mouseenter‘, function () { animate(con, -150, function () { // 当动画执行完毕,就把箭头方向交换 sliderbar.children[0].innerHTML = ‘→‘ }) }) sliderbar.addEventListener(‘mouseleave‘, function () { animate(con, 50, function () { sliderbar.children[0].innerHTML = ‘←‘ }) })
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(); // } callback && callback(); } // 把里面的移动值改为慢慢变小的值 obj.style.left = obj.offsetLeft + step + ‘px‘ }, 15) }
原文:https://www.cnblogs.com/xf2764/p/12702991.html