动画实现滑块的滑动

动画实现滑块的滑动


功能描述

  1. 鼠标经过 sliderbar 就会让 con 滑出
  2. 鼠标离开 sliderbar 就会让 con 收回
  3. con 滑出后,将 改为
  4. con 收回后,将 改为

实现思路

  1. 添加鼠标经过时事件,鼠标经过,将**“问题反馈”**移出
  2. 利用回调函数,将 改为
  3. 添加鼠标离开事件,鼠标离开,将**“问题反馈”**缩回
  4. 利用回调函数,将 改为

代码

<!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>引用animate动画函数</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>
    <!-- 引用animate.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');

        // 鼠标经过 sliderbar 就会让 con 滑动到左侧
        // 鼠标经过,问题反馈移出
        sliderbar.addEventListener('mouseenter', function () {
      
      
            animate(con, -160, function () {
      
      
                // 动画执行完毕,执行回调函数,⬅ 改为 ➡
                sliderbar.children[0].innerHTML = '➡';
            })
        })

        // 鼠标离开 sliderbar 就会让 con 滑动回右侧
        // 鼠标离开,问题反馈缩回
        sliderbar.addEventListener('mouseleave', function () {
      
      
            animate(con, 0, function () {
      
      
                // 动画结束,执行回调函数,➡ 改为 ⬅
                sliderbar.children[0].innerHTML = '⬅';
            });
        })

    </script>
</body>

</html>
// 动画
/**
 * obj          添加该动画的对象
 * target       目标位置
 * callback     回调函数
 *  */
function animate(obj, target, callback) {
    
    

    // 预先清除计时器,防止多次触发动画时,动画速度变快的bug
    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);
}

效果展示

animate.GIF

Supongo que te gusta

Origin blog.csdn.net/m0_47585722/article/details/116954550
Recomendado
Clasificación