问题描述
我正在使用此脚本 (https://codepen.io/bramus/pen/ExaEqMJ) 将活动类应用到页面的内容列表中一段时间。
我知道如果多个标题可见,当前形式的脚本会突出显示多个项目,但我想对其进行调整,以便它选择页面最高的项目。例如,视口中有三个标题可见 - 当前脚本将突出显示内容列表中的所有三个标题,但我希望它只突出显示标题 1,直到我滚动过去:
标题 1
标题 2
标题 3
window.addEventListener('DOMContentLoaded',() => {
const observer = new IntersectionObserver(entries => {
entries.forEach(entry => {
const id = entry.target.getAttribute('id');
if (entry.intersectionRatio > 0) {
document.querySelector(`nav li a[href="#${id}"]`).parentElement.classList.add('active');
} else {
document.querySelector(`nav li a[href="#${id}"]`).parentElement.classList.remove('active');
}
});
});
// Track all sections that have an `id` applied
document.querySelectorAll('section[id]').forEach((section) => {
observer.observe(section);
});
});
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)