js实现水平伸缩导航栏

 

HTML代码:

<body>
    <ul>
        <li><a>page1</a></li>
        <li><a>page2</a></li>
        <li><a>page3</a></li>
        <li><a>page4</a></li>
        <li><a>page5</a></li>
    </ul>
</body>

 

CSS代码:

    <style>
        body,ul{
            margin: 0;
            padding:0;
        }
        ul{
            list-style: none;
            height:40px;
            border-bottom: solid 5px #e4393c;
        }
        li{
            text-align: center;
            float: left;
        }
        a{
            text-decoration: none;
            display: block;
            width:100px;
            height:40px;
            line-height: 40px;
            background-color: #6a6a6a;
            color: #fff;
        }
        a:hover{
            background-color: #e4393c;
        }
    </style>

 

JS代码两种实现方式:

        //原始方式
        window.onload = function () {
            var oA = document.getElementsByTagName('a');

            for(var i=0;i<oA.length;i++){

                oA[i].onmouseover = function(){
                    clearInterval(this.time);
                    var This = this;
                    This.time = setInterval(function(){
                        This.style.width = This.offsetWidth + 10 + 'px';
                        if(This.offsetWidth >= 200){
                            clearInterval(This.time);
                        }
                    },10);
                };

                oA[i].onmouseout = function() {
                    clearInterval(this.time);
                    var This = this;
                    This.time = setInterval(function () {
                        This.style.width = This.offsetWidth - 10 + 'px';
                        if (This.offsetWidth <= 100) {
                            This.style.width = "100px";
                            clearInterval(This.time);
                        }
                    }, 10);
                }
            }
        }

        //动画实现方式
        $(function(){
            $('a').hover(
                function(){
                    $(this).stop().animate({"width":"300px"},100);
                },
                function(){
                    $(this).stop().animate({"width":"100px"},100);
                }
            );
        })

 

 效果:

 

 

 

 

 

 

 

posted @ 2019-11-12 09:51  Fourteen  阅读(575)  评论(0编辑  收藏  举报