要实现不使用jQuery的方式来突出显示活动的锚链接,你可以使用纯JavaScript来实现。下面是一个示例代码:
HTML代码:
Section 1
Content for section 1.
Section 2
Content for section 2.
Section 3
Content for section 3.
JavaScript代码:
// 获取所有锚链接
var links = document.querySelectorAll('nav a');
// 监听滚动事件
window.addEventListener('scroll', function() {
var currentSection = '';
// 遍历所有锚链接
for (var i = 0; i < links.length; i++) {
var section = document.querySelector(links[i].hash);
var sectionTop = section.offsetTop;
var sectionHeight = section.offsetHeight;
// 检查当前滚动位置是否在某个section范围内
if (window.pageYOffset >= sectionTop && window.pageYOffset < sectionTop + sectionHeight) {
currentSection = links[i].hash;
}
}
// 添加活动样式
for (var i = 0; i < links.length; i++) {
links[i].classList.remove('active');
if (links[i].hash === currentSection) {
links[i].classList.add('active');
}
}
});
CSS代码:
nav a.active {
font-weight: bold;
color: red;
}
上述代码会在滚动时,根据滚动位置自动突出显示当前活动的锚链接。