滚动网站内容或到达特定div时如何更新菜单
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了滚动网站内容或到达特定div时如何更新菜单相关的知识,希望对你有一定的参考价值。
基本上,它显示一个菜单,其中包含指向页面各部分的链接,这些链接在用户滚动经过它们时会突出显示。如何突出显示菜单?如何使用html,CSS或javascript实现此目标?
HTML的示例代码:
<section id="main">
<div class="target" id="1">TARGET 1</div>
<div class="target" id="2">TARGET 2</div>
<div class="target" id="3">TARGET 3</div>
<div class="target" id="4">TARGET 4</div>
</section>
<aside id="nav">
<nav>
<a href="#1" class="active">Punkt 1</a>
<a href="#2">Punkt 2</a>
<a href="#3">Punkt 3</a>
<a href="#4">Punkt 4</a>
</nav>
</aside>
答案
这就是您要查找的名为scrollspy。尝试类似的事情:
<section id="main">
<div class="target" id="1">TARGET 1</div>
<div class="target" id="2">TARGET 2</div>
<div class="target" id="3">TARGET 3</div>
<div class="target" id="4">TARGET 4</div>
</section>
<aside id="nav">
<nav>
<a class="link" id="link_1" href="#1">Punkt 1</a>
<a class="link" id="link_2" href="#2">Punkt 2</a>
<a class="link" id="link_3" href="#3">Punkt 3</a>
<a class="link" id="link_4" href="#4">Punkt 4</a>
</nav>
</aside>
a.active {
background-color: #CCCCFF;
}
和JS:
// doesn't require JQuery
function isInViewport(el) {
const rect = el.getBoundingClientRect()
const windowHeight = (window.innerHeight || document.documentElement.clientHeight)
const windowWidth = (window.innerWidth || document.documentElement.clientWidth)
const vertInView = (rect.top <= windowHeight) && ((rect.top + rect.height) >= 0)
const horInView = (rect.left <= windowWidth) && ((rect.left + rect.width) >= 0)
return (vertInView && horInView)
}
window.onscroll = () => {
for(el of document.getElementsByClassName('list')) {
el.classList.remove('active') // reset list
}
// finding element in the viewport
for(el of document.getElementsByClassName('target')) {
if(isInViewport(el)) {
// setting active element
document.getElementById('link_' + el.id).classList.add('active')
}
}
}
这应该对您有用。
以上是关于滚动网站内容或到达特定div时如何更新菜单的主要内容,如果未能解决你的问题,请参考以下文章