<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no" /> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style> * { margin: 0; padding: 0; } ul { list-style: none; } /* 控制其顯示和隱藏 */ .show { display: block !important; } .header { overflow: hidden; height: 25px; width: 100%; height: 25px; line-height: 25px; padding-bottom: 1px; } .header-tab { width: 100%; display: flex; overflow: hidden; white-space: nowrap; overflow-x: scroll; background-color: pink; white-space: nowrap; font-size: 15px; } .header-tab li { cursor: pointer; margin-left: 6px; } .wrapper { height: 600px; width: 100%; margin: 0 auto; } /* 其子元素為隱藏狀態 */ .wrapper>div { display: none; } /* 隱藏滾動條 */ .header-tab::-webkit-scrollbar { display: none } /* 添加下划線 */ .add2line { color: #3385ff; border-bottom: 1px solid #3385ff; } </style> </head> <body> <nav class="header"> <ul class="header-tab" id="box"> <li class="add2line">更新內容</li> <li>關注</li> <li>熱點</li> <li>要聞</li> <li>我的生活</li> <li>國際新聞</li> <li>態度公開課</li> <li>新時代</li> <li>抖音視頻</li> </ul> </nav> <main class="wrapper"> <div class="show content"> 頁面1 </div> <div class="content"> 頁面2 </div> </div> <div class="content"> 頁面3 </div> <div class="content"> 頁面4 </div> <div class="content"> 頁面5 </div> <div class="content"> 頁面6 </div> <div class="content"> 頁面7 </div> <div class="content"> 頁面8 </div> <div class="content"> 頁面9 </div> </main> </body> </html> <script> window.onload = function () { var doc = document isShow() function isShow() { var liArr = doc.querySelectorAll('#box > li') var divArr = doc.querySelectorAll('.wrapper .content') for (var i = 0; i < liArr.length; i++) { liArr[i].index = i; liArr[i].onclick = function () { for (var j = 0; j < liArr.length; j++) { liArr[j].className = '' divArr[j].className = '' } divArr[this.index].className = 'show' liArr[this.index].className = 'add2line' } } } // 當前視窗的寬度 var WINDOW_OFFSETWIDTH = doc.documentElement.clientWidth var liArr = doc.querySelectorAll('#box > li') for (var i = 0; i < liArr.length; i++) { liArr[i].addEventListener('click', function (e) { // 獲取當前點擊元素的寬度 var itemWidth = this.offsetWidth // 當前事件對象相對移動的距離 var moveX = e.target.offsetLeft // 目標居中的距離 = (當前元素距離左邊的相對距離 / 2)+ (視口距離 / 2) var left = moveX - (WINDOW_OFFSETWIDTH / 2) + (itemWidth / 2) doc.getElementById('box').scrollLeft = left }) } } </script>