菜单栏缓动滑动

在这里插入图片描述
offsetLeft获取值四舍五入取整后计算
当差值大于0的时候向上取整,小于0的时候向下取整

代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        *{
            margin:0;
            padding: 0;
        }
        body{
            background: rgba(0,0,0,0.8);
        }
        .box{
            width:800px;
            height:42px;
            background: #ffffff url("images/wifi.png") right center no-repeat;
            margin:200px auto;
            border-radius: 8px;
            position: relative;
        }
        ul{
            list-style: none;
            position: relative;
        }
        li{
            float: left;
            width:83px;
            height:42px;
            text-align: center;
            font:500 16px/42px "微软雅黑";
            cursor: pointer;
            line-height: 42px;
        }
        span{
            position: absolute;
            left:0;
            top:0;
            width:83px;
            height: 42px;
            background:url("images/cloud.gif") no-repeat;
        }
    </style>
    <script>
        window.function () {
            //鼠标放在哪个li,span对应
            var liArr=document.getElementsByTagName("li");
            var liWidth=liArr[0].offsetWidth;
            var span=document.getElementsByTagName("span")[0];
            var count=0;

            for(var i=0;i<liArr.length;i++){
                liArr[i].index=i;
                liArr[i].function () {
                    //让span运动到li的索引值位置
                    animate(span,this.index*liWidth);
                }
                liArr[i].function () {
                    //让span运动到li的索引值位置
                    animate(span,count*imgWidth);
                }
                //点击事件,记录功能
                liArr[i].function () {
                    count=this.index;
                    animate(span,count*imgWidth);
                }
            }
            //缓动动画封装
            function  animate(ele,target) {
                clearInterval(ele.timer);
                ele.timer=setInterval(function () {
                    var step=(target-ele.offsetLeft)/10;
                    //对步长进行二次加工
                    step=step>0?Math.ceil(step):Math.floor(step);
                    //动画原理:目标位置=当前位置+步长
                    ele.style.left=ele.offsetLeft+step+"px";
                    if(Math.abs(target-ele.offsetLeft)<Math.abs(step)){
                        ele.style.left=target+"px";
                        clearInterval(ele.timer);
                    }
                },1);
            }
        }
    </script>
</head>
<body>
    <div class="box">
        <span></span>
        <ul>
            <li>首页新闻</li>
            <li>活动策划</li>
            <li>师资力量</li>
            <li>企业文化</li>
            <li>招聘信息</li>
            <li>公司简介</li>
            <li>上海校区</li>
            <li>广州校区</li>
        </ul>
    </div>
</body>

猜你喜欢

转载自blog.csdn.net/zuo_zuo_blog/article/details/89458919
今日推荐