-第2章 JS方法實現下拉菜單顯示和隱藏


知識點

onmouseover 鼠標經過
onmouseout 鼠標移出
function 關鍵字
getElementsByTagName 獲取一組標簽
length 獲取對象成員個數

思路
給一級菜單添加鼠標事件,經鼠標在一級菜單上時,顯示下面的二級菜單。但是在處理二級菜單之前,先通過 length 判斷一下有沒有二級菜單。

為什么要判斷?
因為比如像 ul.getElementsByTagName('li') 這樣的方式獲取到的是所有 ul 下面的所有 li, 這個 li 可能有很多層。

完整代碼

<!--
Author: XiaoWen
Create a file: 2017-02-27 11:24:01
Last modified: 2017-02-27 16:22:00
Start to work:
Finish the work:
Other information:
-->
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
  <style>
    *{
      margin: 0;
      padding: 0;
    }
    #nav{
      background: #eee;
      width: 600px;
      height: 40px;
      margin: 0 auto;
    }
    ul{
      list-style:none;
    }
    ul li{
      float: left;
      line-height: 40px;
      text-align: center;
      position: relative;
    }
    a{
      text-decoration: none;
      color: #000;
      display: block;
      padding: 0 10px;
      height: 40px;
    }
    a:hover{
      color: #fff;
      background: #666;
    }
    ul li ul li{
      float: none;
      background: #eee;
      margin-top: 2px;
    }
    ul li ul{
      position: absolute;
      left: 0;
      top: 40px;
    }
    ul li ul li a{
      width: 80px;
    }
    ul li ul li a:hover{
      background: #06f;
    }
    ul li ul{
       display: none;
    }
    ul li:hover ul{
      /* display: block; */
    }
  </style>
</head>
<body>
<div id="nav">
  <ul>
    <li><a href="#">一級菜單1</a></li>
    <li><a href="#">一級菜單2</a></li>
    <li>
      <a href="#">一級菜單3</a>
      <ul>
        <li><a href="#">二級菜單1</a></li>
        <li><a href="#">二級菜單2</a></li>
        <li><a href="#">二級菜單3</a></li>
      </ul>
    </li>
    <li><a href="#">一級菜單4</a></li>
    <li><a href="#">一級菜單5</a></li>
    <li><a href="#">一級菜單6</a></li>
  </ul>
</div>
<script>
window.onload=function(){
  var a_li=document.getElementsByTagName('li');
  for(var i=0;i<a_li.length;i++){
    //獲取 li 下面的 二級菜單 ul ,
    //如果能獲取到的個數是 1 個以上,
    //條件成立,把 li 下面 的 二級菜單 ul 顯示。
    if(a_li[i].getElementsByTagName('ul').length){
      a_li[i].onmouseover=function(){
        this.getElementsByTagName('ul')[0].style.display="block"
      }
      a_li[i].onmouseout=function(){
        this.getElementsByTagName('ul')[0].style.display="none"
      }
    }
  }
}
</script>
</body>
</html>

總結

css 中的鼠標偽類已經注釋了的 ul li:hover ul{/* display: block; */} ,現在是用 js 實現,所以用不着這個鼠標偽類了。

通過這種方法寫的 js 下拉菜單,可以避免 ie6 下的不支持非 a 標簽偽類的情況。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM