<html> <head> <meta charset="utf-8" /> <title></title> <style> html,body{ height: 100%; 100%; } * { padding: 0; margin: 0; } .menu_nav { position: fixed; left: 45%; } .menu_nav li { display: inline-block; } .model { height: 300px; 100%; } .active { background: red } .warp{ height: 100%; overflow-y: auto; } </style> </head> <body> <div class="warp" id="warp"> <div class="menu_nav"> <ul id="nav"> <li class="active"> <a href="#1">1</a> </li> <li> <a href="#2">2</a> </li> <li> <a href="#3">3</a> </li> <li> <a href="#4">4</a> </li> <li> <a href="#5">5</a> </li> <li> <a href="#6">6</a> </li> <li> <a href="#7">7</a> </li> </ul> </div> <div class="menu_con"> <div class="model"> <p>我是1</p> </div> <div class="model"> <p>我是2</p> </div> <div class="model"> <p>我是3</p> </div> <div class="model"> <p>我是4</p> </div> <div class="model"> <p>我是5</p> </div> <div class="model"> <p>我是6</p> </div> <div class="model"> <p>我是7</p> </div> </div> </div> </body> <script> let $warp = document.getElementById('warp'); let arrHeight = getHeight(); $warp.onscroll = function(){ let $nav = document.getElementById('nav'); let $LI_list = $nav.childNodes; let len = $LI_list.length; let nav = []; //导航元素数组 for(let i = 0; i < len; i++){ if ($LI_list[i].tagName === "LI") { nav.push($LI_list[i]); } } // 根据滚动事件 计算当前应该是那个模块该激活 let top = this.scrollTop; //表示滚动条滚动的高度 let index = getIndex(top); // 判断 当前滚动模块 那个激活 let len1 = nav.length; for(let i = 0; i < len1; i ++){ let cls = nav[i].className; if (cls && i !== index) { nav[i].className = ''; } if (i == index){ nav[i].className = 'active'; } } } // 获取当前激活模块的 index function getIndex(top){ for( let i in arrHeight){ if (top < arrHeight[i]) { return i; } } } // 获取 所有模块的高度 装成数组,然后滚动判断是到那个模块了 function getHeight() { let $doms = document.getElementsByClassName('model'); let len = $doms.length; let data = []; for(let i = 0; i < len; i++){ let h = $doms[i].clientHeight; if (i == 0) { //第一个 有头部 元素 高度 需要加上 , 最后一个 ,有底部 高度需要加上, 每一个模块之间如果有间距 也需要加上 data[i] = h }else{ data[i] = data[i - 1] + h } } return data; } </script> </html>