js下拉菜單制作

2020-09-17 17:30 更新

一、用js通過下拉菜單來實(shí)現(xiàn)div的隱藏和顯示

思路:利用value屬性獲取下拉菜單的選項(xiàng)→根據(jù)選項(xiàng)決定div的狀態(tài)→利用style.display樣式隱藏或顯示div。實(shí)例演示如下:

代碼

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>W3Cschool(w3cschool.cn)</title>
</head>
<body>
  <select id="test_select">
    <option value="1">顯示</option>
    <option value="2">隱藏</option>
  </select>
  <div id="test">我是一個(gè)div么呀我是一個(gè)div</div>
  <script>
    window.onload = function () {
      var obj_select = document.getElementById("test_select");
      var obj_div = document.getElementById("test");
      obj_select.onchange = function () {
        obj_div.style.display = this.value == 1 ? "block" : "none";
      }
    }
  </script>
</body>
</html>


效果演示

js下拉菜單


二、鼠標(biāo)滑過出現(xiàn)下拉菜單的js做法

大致思路如下:先給菜單box定好寬高加上position:relative;再給里面的內(nèi)容定上與之相同的寬高;然后給里面的下拉 二級(jí)菜單加上寬度絕對(duì)定位。

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>W3Cschool(w3cschool.cn)</title>
  <style>
    * {
      margin: 0;
      padding: 0;
    }
    li {
      list-style-type: none;
    }
    a {
      text-decoration: none;
      font-size: 14px;
    }
    .nav {
      margin: 100px;
    }
    .nav>li {
      position: relative;
      float: left;
      width: 80px;
      height: 41px;
      text-align: center;
    }
    .nav li a {
      display: block;
      width: 100%;
      height: 100%;
      line-height: 41px;
      color: #333;
    }
    .nav>li>a:hover {
      background-color: #eee;
    }
    .nav ul {
      display: none;
      position: absolute;
      top: 41px;
      left: 0;
      width: 100%;
      border-left: 1px solid #FECC5B;
      border-right: 1px solid #FECC5B;
    }
    .nav ul li {
      border-bottom: 1px solid #FECC5B;
    }
    .nav ul li a:hover {
      background-color: #FFF5DA;
    }
  </style>
</head>
<body>
  <ul class="nav">
    <li>
      <a href="javascript:;">下拉</a>
      <ul>
        <li><a href="javascript:;">下拉1</a></li>
        <li><a href="javascript:;">下拉2</a></li>
        <li><a href="javascript:;">下拉3</a></li>
        <li><a href="javascript:;">下拉4</a></li>
      </ul>
    </li>
  </ul>
  <script>
    var lis = document.querySelector('.nav').children;
    for (var i = 0; i < lis.length; i++) {
      lis[i].onmouseover = function () {
        this.children[i].style.display = 'block';
      }
      lis[i].onmouseout = function () {
        this.children[i].style.display = 'none';
      }
    }
  </script>
</body>
</html>



以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)