我正在学习如何执行此左侧菜单: http://js.devexpress.com/New/15_2/#HTML_5_JS_Core 当您向下滚动页面时,“事件”菜单项会发生变化。
附: 这种类型的菜单有名称吗?
问候, 亚尼夫
最佳答案
滚动导航
这就是我们对此类导航栏的称呼。基本上,您必须监听滚动事件并计算当前视口(viewport)中的元素,而不是向导航中添加一个标记当前菜单元素的类。
有a nice demo built in jQuery但因为 jQuery 已经成为过去,所以我用 Vanilla JS 构建了一个。请参阅评论以获取解释。
有不同的方法来定义当前元素。在我的示例中,它是最后一个,其顶行刚刚超过浏览器的顶行。
工作演示
window.onscroll = onScroll;
function onScroll() {
var removeActiveClass = function (elements) {
for (var i = 0; i < elements.length; ++i) {
elements[i].classList.remove('active');
}
}
var anchors = document.querySelectorAll('#menu-center a');
var previousRefElement = null;
for (var i = 0; i < anchors.length; ++i) {
// Get the current element by the id from the anchor's href.
var currentRefElement = document.getElementById(anchors[i].getAttribute('href').substring(1));
var currentRefElementTop = currentRefElement.getBoundingClientRect().top;
// Searching for the element whose top haven't left the top of the browser.
if (currentRefElementTop <= 0) {
//The browser's top line haven't reached the current element, so the previous element is the one we currently look at.
previousRefElement = anchors[i];
// Edge case for last element.
if (i == anchors.length - 1) {
removeActiveClass(anchors);
anchors[i].classList.add("active");
}
} else {
removeActiveClass(anchors);
previousRefElement.classList.add("active");
break;
}
}
}
body, html {
margin: 0;
padding: 0;
height: 100%;
width: 100%;
}
.menu {
width: 100%;
height: 75px;
position: fixed;
background-color:rgba(4, 180, 49, 0.6);
}
#menu-center {
width: 980px;
height: 75px;
margin: 0 auto;
}
#menu-center ul {
margin: 15px 0 0 0;
}
#menu-center ul li {
list-style: none;
margin: 0 30px 0 0;
display: inline;
}
.active {
font-size: 14px;
color: #fff;
text-decoration: none;
line-height: 50px;
}
a {
font-size: 14px;
color: black;
text-decoration: none;
line-height: 50px;
}
.content {
height: 100%;
width: 100%;
}
#portfolio {background-color: grey;}
#about {background-color: blue;}
#contact {background-color: red;}
<div class="menu">
<div id="menu-center">
<ul>
<li><a class="active" href="#home">Home</a></li>
<li><a href="#portfolio">Portfolio</a></li>
<li><a href="#about">About</a></li>
<li><a href="#contact">Contact</a></li>
</ul>
</div>
</div>
<div id="home" class="content"></div>
<div id="portfolio" class="content"></div>
<div id="about" class="content"></div>
<div id="contact" class="content"></div>
关于javascript - 如何创建 "active"元素跟随页面内容位置的侧边菜单?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37360616/