[英]Menu active class on scrolling - Issue with section margins
我正在嘗試做的是:
當用戶在我的網站上上下滾動(單頁,多個部分)時,菜單將突出顯示該用戶當前所在頁面的哪個部分。
我做了什么:
我有一個工作菜單,以便當鏈接的部分當前滾動到該菜單時,它將把類更改為“活動”。
問題:
每個部分的上邊距約為50-100像素。 當前的javascript代碼無法處理此問題,而是如果用戶位於兩個部分之間,則將其從所有菜單項中完全刪除。
JS小提琴: http : //jsfiddle.net/d4yqA/3/
HTML:
<div id="headerWrapperFixed">
<div id="headerFixed">
<div id="fixedMenu">
<ul>
<li><a href="#home">Home</a>
</li>
<li><a href="#about-us">About Us</a>
</li>
<li><a href="#pricing">Pricing</a>
</li>
</li>
</ul>
</div>
</div>
</div>
<div id="home">
<h1>HOME</h1>
</div>
<div id="about-us">
<h1>ABOUT US</h1>
</div>
<div id="pricing">
<h1>PRICING</h1>
</div>
CSS:
#headerWrapperFixed {
top:0;
position:fixed;
height:30px;
width:100%;
background-color:RGB(38, 38, 38);
}
#headerFixed {
width:1100px;
height:30px;
background-color:RGB(200, 200, 200);
}
#fixedMenu {
position:relative;
width:700px;
height:30px;
}
#fixedMenu ul {
list-style-type: none;
margin: 0;
padding: 0;
width:650px;
height:30px;
}
#fixedMenu li {
display: table-cell;
width:120px;
height:30px;
text-align:center;
vertical-align:middle;
}
li.active a, #fixedMenu li>a:hover, a.active {
color:#FF0000 !important;
}
#home {
height:800px;
background-color:rgb(100, 100, 100);
margin-top:100px;
}
#about-us {
height:800px;
background-color:rgb(200, 200, 200);
margin-top:100px;
}
#pricing {
margin-top:100px;
height:800px;
}
h1 {
margin:0;
padding-top:50px;
}
Javascript:
$(window).scroll(function () {
var scrollPos = $(document).scrollTop() + 40;
$('#fixedMenu a').each(function () {
var currLink = $(this);
var refElement = $(currLink.attr("href"));
if (refElement.position().top <= scrollPos && refElement.position().top + refElement.height() > scrollPos) {
$('#fixedMenu ul li').removeClass("active");
currLink.addClass("active");
} else {
currLink.removeClass("active");
}
});
});
如果要在滾動到頁邊距時僅將活動類保留在當前部分上,只需將其添加到等式的右側
if (refElement.position().top <= scrollPos + 120 && refElement.position().top + refElement.height() > scrollPos + 0) {
或者,如果您要轉到下一個,請從右側減去它
if (refElement.position().top <= scrollPos -120&& refElement.position().top + refElement.height() > scrollPos) {
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.