用面向对象思想实现菜单显示与隐藏

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<style>
    *{margin:0;padding:0;}
    a{text-decoration:none;}
    #menu{position: fixed;left:-80px; bottom: 100px;}
    #menu ul{text-align: center;float:left;list-style: none;}
    #menu ul li{height:20px;width:80px;font-size:12px;line-height: 20px;background: #999;
        border-bottom:1px solid #ccc;}
    #menu ul li a{display: block; width:100%;height:100%; color:#fff;}
    #menu p{float:left;line-height: 20px;position: relative;top:22px;margin-left:4px;background: rgb(223, 168, 67);}
</style>

<body>
    <div id="menu">
        <ul>
            <li><a href="">list1</a></li>
            <li><a href="">list2</a></li>
            <li><a href="">list3</a></li>
            <li><a href="">list4</a></li>
        </ul>
        <p>菜<br/>单</p>
    </div>
</body>
<script>
    function Move(id,speed){
        this.timer = null;                                //把timer声明成构造函数属性,否则定时器清除的不是一个变量,无法实现定时器清除
        this.speed = speed;
        this.menu = document.getElementById(id);
        let _this = this;
        this.menu.onmouseover = function(){
            _this.funcStart(this,_this,0);
        };
        this.menu.onmouseout = function(){
            _this.funcStart(this,_this,-80);        //参数分别表示创建的对象,菜单,边界值
        };
    }

    Move.prototype.funcStart = function(oMenu,obj,iTarget){         //用三个形参接收数据
        clearInterval(obj.timer);
        obj.timer = setInterval(function(){
            if(iTarget >= 0){
                if(oMenu.offsetLeft >= iTarget){
                    clearInterval(obj.timer);
                    oMenu.style.left = iTarget;
                }else{
                    oMenu.style.left = oMenu.offsetLeft + obj.speed + "px";
                }
            }else{
                if(oMenu.offsetLeft <= iTarget){
                    clearInterval(obj.timer);
                    oMenu.style.left = iTarget + "px";              //记得加px
                }else{
                    oMenu.style.left = oMenu.offsetLeft - obj.speed + "px";
                }
            }
        },10);
    }
    window.onload = function(){
        new Move('menu',5);
    }
</script>
</html>        

 

posted @ 2020-08-12 18:19  咚咚呱  阅读(151)  评论(0编辑  收藏  举报