我正试图从我即将进行的项目中抛弃 jQuery。我找到了一种使用纯 Vanilla JS 在滚动上创建粘性导航的方法,并希望导航上的链接在到达相应部分时更改其活动状态。
下面是我提出的工作解决方案,但我确信可以改进代码以编程方式工作,而无需为每个元素选择和创建条件。
我也使用了很多不同的选择器,我很确定一定有办法改进它,也许在循环中使用querySelectorAll和添加一个,但我也不能让它工作。谢谢你的帮助!eventListenerforEach
// select links
const allLinks = document.querySelectorAll('header nav ul li');
const linkTop = document.querySelector('#linkTop');
const linkAbout = document.querySelector('#linkAbout');
const linkServices = document.querySelector('#linkServices');
const linkClients = document.querySelector('#linkClients');
const linkContact = document.querySelector('#linkContact');
// select sections
const sectionTop = document.querySelector('#top');
const sectionAbout = document.querySelector('#about');
const sectionServices = document.querySelector('#services');
const sectionClients = document.querySelector('#clients');
const sectionContact = document.querySelector('#contact');
function changeLinkState() {
// home
if (window.scrollY >= sectionTop.offsetTop) {
allLinks.forEach(link => {
link.classList.remove('active');
});
linkTop.classList.add('active'); …Run Code Online (Sandbox Code Playgroud)