鼠标移动上去之后元素向外移动,移出后元素回走效果

    技术2022-07-13  89

    鼠标移动上去效果如下 源代码:

    <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Document</title> <style> * { margin: 0; padding: 0; } .box { position: fixed; top: 50%; text-align: center; line-height: 40px; transform: translate(0, -50%); right: 0; width: 40px; height: 40px; color: white; background-color: purple; cursor: pointer; } .div { position: absolute; left: 0; top: 0; width: 200px; background-color: purple; z-index: -1; } </style> </head> <body> <div class="box"> <span>&lt-</span> <div class="div">问题</div> </div> <script> var div = document.querySelector('.div'); var box = document.querySelector('.box') var span = document.querySelector('span') function style() { span.innerHTML = '->' } box.addEventListener('mouseenter', function () { move(div, -(div.clientWidth - box.clientWidth), style) }) box.addEventListener('mouseleave', function () { move(div, 0) span.innerHTML = '<-' }) // 用途:在页面上实现来回移动的盒子 // obj:要移动的对象元素 // target:目标位置 // callback:回调函数,跑完之后做什么操作 function move(obj, target, callback) { // 先清除,以免产生过多的定时器 clearInterval(obj.timer) obj.timer = setInterval(function () { //step后面的公式为(目标位置-当前位置)/10 作为缓慢移动的公式 var step = (target - obj.offsetLeft) / 10 // 如果是正着走就往上取整,如果倒着走就是地板取整。能得出比较精确的数 step = step > 0 ? Math.ceil(step) : Math.floor(step) obj.style.left = obj.offsetLeft + step + 'px' if (obj.offsetLeft == target) { clearInterval(obj.timer) if (callback) { callback() //这里是回调函数 } } }, 10); } </script> </body> </html>
    Processed: 0.010, SQL: 9