// 概览 const myElement = document.getElementById('navigation'); const header = document.getElementsByTagName('header'); const elements = document.getElementsByClassName('anchorLocation'); const dwEles = document.getElementsByClassName('dw1'); const elementsArray = Array.from(elements); const dwElesArray = Array.from(dwEles); (function() { let activeKey = 0; window.addEventListener('scroll', function () { var scrollTop = window.pageYOffset || document.documentElement.scrollTop; // 获取页面滚动距离 if (scrollTop >= window.innerHeight * 0.75) { myElement.style.position = 'fixed'; // 如果子元素滑到最顶部,则设置为固定定位 myElement.style.top = '0'; if(header[0]) { header[0]['style']['display'] = 'none'; } } else { myElement.style.position = ''; // 否则,清空定位属性,使元素回到相对定位(默认值) if(header[0]) { header[0]['style']['display'] = 'block'; } } // 锚点定位高亮 elementsArray.forEach((item, index) => { if (scrollTop + myElement.offsetHeight >= item.offsetTop) { activeKey = index; } }); dwElesArray.forEach((ele,index) => { const a = ele.querySelector('a'); if (index == activeKey) a.classList.add('navTitle'); else a.classList.remove('navTitle'); }); }); }) (); // 锚点定位 function anchorLocation(e,key) { const targetElement = elementsArray[key]; targetElement.scrollIntoView({ behavior: 'smooth', block: 'start' // Align to the top of the viewport }); }