1. 程式人生 > 實用技巧 >用面向物件思想實現選單顯示與隱藏

用面向物件思想實現選單顯示與隱藏

<!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>