在滚动和单击时添加活动类(Active Class)
为了实现这个效果,我们可以使用JavaScript。我们需要为每个锚点(Anchor)创建一个单击事件和一个滚动事件。
HTML 模板示例:
Section 1
Content goes here.
Section 2
Content goes here.
Section 3
Content goes here.
JavaScript 代码示例:
document.addEventListener("DOMContentLoaded", function() {
// 获取每个锚点
var anchors = document.querySelectorAll("nav a");
// 添加点击事件 listeners 到每个锚点
for (var i = 0; i < anchors.length; i++) {
anchors[i].addEventListener("click", function(event) {
event.preventDefault();
var targetId = this.getAttribute("href");
var targetElement = document.querySelector(targetId);
targetElement.scrollIntoView({ behavior: "smooth" });
});
}
// 添加滚动事件 listeners 到每个 section
var sections = document.querySelectorAll("section");
var scrollPosition = window.pageYOffset || document.documentElement.scrollTop;
function onScroll() {
scrollPosition = window.pageYOffset || document.documentElement.scrollTop;
for (var i = 0; i < sections.length; i++) {
var currentSection = sections[i];
var currentSectionTopOffset = currentSection.offsetTop - 50;
var currentSectionId = currentSection.getAttribute("id");
if (scrollPosition >= currentSectionTopOffset) {
document.querySelector("nav a.active").classList.remove("active");
document.querySelector("nav a[href='#" + currentSectionId + "']").classList.add("active");
}
}
}
onScroll();
window.addEventListener("scroll", function() {
onScroll();
});
});
在 CSS 中,我们可以为活动类(Active Class)添加样式:
nav a.active {
color: red;
}
当滚动或