【发布时间】:2017-04-24 03:44:53
【问题描述】:
我希望导航链接具有“活动”类并在滚动时进行更改。我仅在用户单击链接时才工作的代码。如果用户手动滚动页面,则活动类不会改变。有什么建议吗?
$(document).ready(function () {
$(document).on("scroll", onScroll);
//smoothscroll
$('a[href^="#"]').on('click', function (e) {
e.preventDefault();
$(document).off("scroll");
$('a').each(function () {
$(this).removeClass('active');
})
$(this).addClass('active');
var target = this.hash,
menu = target;
$target = $(target);
$('html, body').stop().animate({
'scrollTop': $target.offset().top+2
}, 700, 'swing', function () {
window.location.hash = target;
$(document).on("scroll", onScroll);
});
});
});
function onScroll(event){
var scrollPos = $(document).scrollTop();
$('nav a').each(function () {
var currLink = $(this);
var refElement = $(currLink.attr("href"));
if (refElement.position().top <= scrollPos && refElement.position().top + refElement.height() > scrollPos) {
$('nav ul li a').removeClass("active");
currLink.addClass("active");
}
else{
currLink.removeClass("active");
}
});
}
<!-- navigation -->
<nav>
<ul>
<li><a href="#bmi">text</a></li>
<li><a href="#health">text</a></li>
<li><a href="#home" class="active">text</a></li>
</ul>
</nav>
</header>
<section id="home">
</section>
<section id="health">
</section>
<section id="bmi">
</section>
【问题讨论】:
-
你能分享你的html吗?
-
我添加了导航和部分 html