我正在为我的大学节目设计一个网站。这是一个单页水平滚动网站。我想知道如何突出导航栏上的当前链接。这可能看起来像一个重复的问题,但现有的答案都没有帮助我。
这就是我的代码。
HTML:
<div id="container">
<nav id="menubar">
<div id="logo"><img src="img/logo.png"/></div>
<div id="bar">
<span class="fest"><a href="#home">Home</a></span>
<span class="fest"><a href="#aboutUs">About Us</a></span>
<span class="fest"><a href="#events">Events</a></span>
<span class="fest"><a href="#schedule">Schedule</a></span>
<span class="fest"><a href="#gallery">Gallery</a></span>
<span class="fest"><a href="#people">People</a></span>
<span class="fest"><a href="#sponsors">Sponsors</a></span>
<span class="fest"><a href="#reachUs">Reach Us</a></span>
</div>
</nav>
<section id="home"></section>
<section id="aboutUs"></section>
<section id="events"></section>
//more
</div>
CSS :(只有相关的)
body,html {
height: 100%;
margin:0;
}
#container {
height: 100%;
width: 800%;
margin: auto;
overflow-y: hidden;
overflow-x: scroll;
white-space: nowrap;
font-size: 0;
}
#bar .fest a {
font-weight: normal;
font-size: 1.5vw;
color: black;
text-decoration: none;
}
JQuery的:
var aChildren = $("#bar .fest").children();
var aArray = [];
for (var i=0; i < aChildren.length; i++) {
var aChild = aChildren[i];
var ahref = $(aChild).attr('href');
aArray.push(ahref);
}
$(window).scroll(function(){
var windowPos = $(window).scrollLeft();
for (var i=0; i < aArray.length; i++) {
var theID = aArray[i];
var divPos = $(theID).offset().left;
var divWidth = $(theID).width();
if (windowPos >= divPos && windowPos < (divPos + divWidth)) {
$("#bar .fest a[href='"+theID+"']").css("color","red");
} else {
$("#bar .fest a[href='"+theID+"']").css("color","black");
}
}
});
这是我从各种来源获取的代码(它不起作用)。这是什么错误?它是否与我在#container div而不是正文中滚动的事实有关?
答案 0 :(得分:0)
试试这段代码。
var topMenu = $("#bar"),
topMenuHeight = topMenu.outerHeight()+15,
// All list items
menuItems = topMenu.find("a"),
// Anchors corresponding to menu items
scrollItems = menuItems.map(function(){
var item = $($(this).attr("href"));
if (item.length) { return item; }
});
// Bind to scroll
$(window).scroll(function(){
// Get container scroll position
var fromTop = $(this).scrollTop()+topMenuHeight;
// Get id of current scroll item
var cur = scrollItems.map(function(){
if ($(this).offset().top < fromTop)
return this;
});
// Get the id of the current element
cur = cur[cur.length-1];
var id = cur && cur.length ? cur[0].id : "";
// Set/remove active class
menuItems
.parent().removeClass("active")
.end().filter("[href=#"+id+"]").parent().addClass("active");
});