1. 程式人生 > 實用技巧 >js 實現tab選項卡

js 實現tab選項卡

選項卡實現邏輯: 1、事件:onmouseoveronmouseout 2、滑鼠移入:移動到哪個選項卡,哪個的背景顏色變成紅色 滑鼠移出:移出哪個選項卡,哪個的背景變白色 3、滑鼠點選選項卡 1)設定點選的選項卡的索引 2)滑鼠移入時,先讓所有的圖片隱藏,再讓對應的圖片顯示 3)滑鼠移出選項卡時,預設顯示第一張圖片
<style type="text/css">
    ul,
    li,
    div {
      margin: 0;
      padding: 0;
    }

    ul {
      width: 220px;
      line-height: 40px;
      display: flex;
      border: 1px solid #ccc;
      border-bottom: 0;
      font-size: 18px;
    }

    ul li {
      list-style: none;
      flex: 1
; text-align: center; border-right: 1px solid #ccc; } ul li:last-child { border-right: 0; } .box { position: relative; width: 220px; height: 220px; border: 1px solid #cecece; overflow: hidden; } img { position: absolute; left
: 0; top: 0; display: none; } img:first-child { display: block; } </style> </head> <body> <ul> <li>體育</li> <li>財經</li> <li>新聞</li> </ul> <div class="box"> <img src="./img/1.jpg" alt
=""> <img src="./img/2.jpg" alt=""> <img src="./img/3.jpg" alt=""> </div> <script type="text/javascript"> var aLi = document.getElementsByTagName("li"); var aImg = document.getElementsByTagName("img"); var oUl = document.querySelector("ul"); for (let i = 0; i < aLi.length; i++) { // 先設定對應的陣列索引 aLi[i].index = i; aLi[i].onmouseover = function () { for (let j = 0; j < aImg.length; j++) { aImg[j].style.display = "none"; } this.style.backgroundColor = "pink"; aImg[this.index].style.display = "block"; } aLi[i].onmouseout = function () { this.style.backgroundColor = "white"; aImg[this.index].style.display = "none"; } } oUl.onmouseout = function () { aImg[1].style.display = "block"; } </script>