#javascript #html #css
#javascript #HTML #css
Вопрос:
Я пытаюсь сделать меню навигации по активному состоянию таким, чтобы привязанные ссылки выделялись при прокрутке до каждого раздела. Я только что протестировал свой сайт и получил следующие ошибки:
Неперехваченное исключение DOMException: не удалось выполнить ‘querySelector’ для ‘Document’: Предоставленный селектор пуст.
NodeList.forEach ()
Ошибки относятся к этому коду:
navLinks.forEach(link => {
let section = document.querySelector(link.hash);
Я никогда не видел их раньше и не знаю, что мне делать. Спасибо!
--HTML--
<div class="menu">
<div class="top-nav">
<div class="logo">
<h1>Store</h1>
</div>
<div class="close">
<i class="bx bx-x"></i>
</div>
</div>
<ul class="nav-list">
<li class="nav-item"><a class="nav-link active" href="#home">Home</a></li>
<li class="nav-item"><a href="#products" class="nav-link">Products</a></li>
<li class="nav-item"><a href="#featured" class="nav-link">Featured</a></li>
<li class="nav-item"><a href="#best-sellers" class="nav-link">Best Sellers</a></li>
<li class="nav-item"><a href="#contact" class="nav-link">Contact</a></li>
<li class="nav-item"><a href="#" class="nav-link icon"><i class="bx bx-shopping-bag"></i></a></li>
</ul>
</div>
<main>
<section class="section featured">
<div class="title">
<h1 id="products">Products</h1>
</div>
</section>
<section class="section featured">
<div class="title">
<h1 id="featured">Featured</h1>
</div>
</section>
<section class="section featured">
<div class="title">
<h1 id="best-sellers">Best Sellers</h1>
</div>
</section>
</main>
<footer id="footer" class="section footer">
<div class="footer-title">
<h1 id="contact">Contact</h1>
</div>
</footer>
--JS--
//Change navigation style on scroll
window.addEventListener('scroll', event => {
let scrollLink = document.querySelector('a.nav-link');
(window.scrollY >= 45) ? scrollLink.classList.add('scroll') : scrollLink.classList.remove('scroll');
});
//Active navigation on scroll
window.addEventListener('scroll', event => {
let navLinks = document.querySelectorAll('a');
let fromTop = window.scrollY;
navLinks.forEach(link => {
let section = document.querySelector(link.hash);
if (
section.offsetTop <= fromTop amp;amp;
section.offsetTop section.offsetHeight > fromTop
) {
link.classList.add('active');
} else {
link.classList.remove('active');
}
});
});
--CSS--
a {
color: inherit;
text-decoration: none;
}
a:hover,
a:focus {
color: #fa448c;
text-decoration: underline;
}
a.active {
padding: 8px 15px;
display: block;
text-transform: capitalize;
background-color: #fa448c;
color: #fff;
}
li {
list-style-type: none;
}
Комментарии:
1. Здравствуйте. Сделайте минимальный воспроизводимый пример с вашим проблемным местом в коде, пожалуйста.
2. Привет, я добавил свой код, спасибо!
Ответ №1:
Этот код означает , что количество sections
должно соответствовать количеству тегов a
.
Я немного подправил ваш код, а также закомментировал первый и последний a
тег. Посмотрите, как это работает. Но нет необходимости останавливаться на достигнутом. Необходимо исключить первый и последний тег при доступе, используя метод querySelectorAll(".nav-list a")
.
let mainNavLinks = document.querySelectorAll(".nav-list a");
window.addEventListener("scroll", event => {
let fromTop = window.scrollY;
mainNavLinks.forEach(link => {
let section = document.querySelector(link.hash);
if (
section.offsetTop <= fromTop amp;amp;
section.offsetTop section.offsetHeight > fromTop
) {
link.classList.add("active");
} else {
link.classList.remove("active");
}
});
});
.menu {
position: sticky;
top: 0;
background-color: white;
}
a {
color: inherit;
text-decoration: none;
}
a:hover,
a:focus {
color: #fa448c;
text-decoration: underline;
}
.active {
padding: 8px 15px;
display: block;
text-transform: capitalize;
background-color: #fa448c;
color: #fff;
}
li {
list-style-type: none;
}
#products {
background-color: red;
height: 500px;
}
#featured {
background-color: green;
height: 500px;
}
#best-sellers {
background-color: yellow;
height: 500px;
}
#contact {
background-color: grey;
height: 500px;
}
--HTML--
<div class="menu">
<div class="top-nav">
<div class="logo">
<h1>Store</h1>
</div>
<div class="close">
<i class="bx bx-x"></i>
</div>
</div>
<ul class="nav-list">
<!--li class="nav-item"><a class="nav-link active" class="home" href="#home">Home</a></li-->
<li class="nav-item"><a href="#products" class="nav-link">Products</a></li>
<li class="nav-item"><a href="#featured" class="nav-link">Featured</a></li>
<li class="nav-item"><a href="#best-sellers" class="nav-link">Best Sellers</a></li>
<li class="nav-item"><a href="#contact" class="nav-link">Contact</a></li>
<!--li class="nav-item"><a href="#" class="nav-link icon"><i class="bx bx-shopping-bag"></i></a></li-->
</ul>
</div>
<div class="sections">
<div id="products">"But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?"</div>
<div id="featured">"But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?"</div>
<div id="best-sellers">"But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?"</div>
<div id="contact">"But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?"</div>
</div>
Комментарии:
1. Спасибо! Я только что ввел код и получил те же ошибки. Неперехваченное исключение DOMException: не удалось выполнить ‘querySelector’ для ‘Document’: Предоставленный селектор пуст. NodeList.forEach () Я добавил свой код раздела в свой вопрос, приношу свои извинения за то, что не добавил его ранее.