js动画函数实现侧边栏动态显示内容

功能概要
  1. 鼠标悬浮侧边栏 弹出数据框 同时指示图标进行变化
  2. 效果图
    效果图
实现原理
  1. 实现过程有两部分组成:显示箭头,以及显示内容盒子
  2. 通过鼠标悬浮以及离开注册监听事件,监听事件中调用动画函数
  3. 动画函数事件步骤:
    1. 通过设置定时器setInterval不断改变显示内容盒子的e.style.left位置
    2. 并通过移动目标位置与当前内容盒子左偏移offsetLeft来控制移动步数,实现缓动动画
    3. 结束条件:内容盒子左偏移等于目标位置
    4. 设置回调函数在结束定时器时设置显示箭头方向
注意点
  1. 移动步数需要考虑在前进/后退时,选取的取整函数不一样
  2. 在chrome中进行测试的时候,内容盒子的offsetLeft一直处于不变状态,也即出现了obj.offsetLeft - 1一直等于 obj.offsetLeft,进行bug调试还没有找出问题,但是在火狐等其他浏览器都是Ok的。还是挺懵的,如果有人明白为什么出现这种情况,还望指教!
代码实现

html

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>practice1</title>
    <link href="../css/practive1.css" rel="stylesheet"/>
    <script src="../js/animate.js"></script>
    <script type="text/javascript" src="../js/practice1.js"></script>
</head>

<body>
<div class="sidderbar">
    <span>⬅</span>
    <div class="con">展示出来</div>
</div>
</body>

</html>

css


.sidderbar {
    position: fixed;
    top: 100px;
    right: 0;
    width: 40px;
    height: 40px;
    text-align: center;
    line-height: 40px;
    background-color: #fff;
}

.con {
    position: absolute;
    left: 0;
    top: 0;
    width: 200px;
    height: 40px;
    line-height: 40px;
    background-color: #84c170;
    z-index: -9;
}

animate.js

/**
 * 动画封装
 * @param obj 移动对象
 * @param target 移动目标位置
 * @param timeout 每次移动间隔
 */
function animate(obj, target, timeout,callback) {
    // 清空已有的定时器
    clearInterval(obj.timer);
    // 为每个对象开辟一个定时器
    obj.timer = setInterval(function () {
        // 移动步长
        var step = (target - obj.offsetLeft) / 10;
        // 判断是否为前进还是后退
        step = step > 0? Math.ceil(step): Math.floor(step);
        console.log('step = ' + step);
        if (obj.offsetLeft == target) {
            clearInterval(obj.timer);
            // 改变状态
           if (callback) {
               callback();
           }
        }
        obj.style.left = obj.offsetLeft + step + 'px';
    },timeout)
}

practice.js

window.addEventListener('pageshow',function () {
    var sidderbar = document.querySelector('.sidderbar');
    var con = document.querySelector('.con');

    sidderbar.addEventListener('mouseenter',function () {
        // 向左移动 con 盒子宽度减去 父盒子sibberbar宽度 其中left绝对于父盒子的距离
        animate(con,sidderbar.offsetWidth - con.offsetWidth  ,15,function () {
                sidderbar.children[0].innerHTML = '➡';
        });
    })

    sidderbar.addEventListener('mouseleave',function () {
        animate(con,0,15,function () {
            sidderbar.children[0].innerHTML = '⬅';
        });
    })

})

猜你喜欢

转载自blog.csdn.net/chen__cheng/article/details/113729031