我要做的是:
当用户在我的网站上下滚动(单页,多个部分)时,菜单将突出显示用户当前所在页面的哪个部分。
我做了什么:
我有一个菜单工作,以便当链接部分当前滚动到时,它会将类更改为“活动”。
问题:
每个部分的上边距约为50 - 100px。当前的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");
}
});
});
答案 0 :(得分:1)
如果您只想在滚动到边距时将活动类保留在当前部分,只需将其添加到等式的右侧
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) {