这是一个单页网站,其中父菜单项锚定到内容区域中的部分。除了平滑滚动之外,一切都已锚定并正常工作。
当" $(。nav a)"" $(。nav a)"时,如何正确设置平滑滚动?点击了吗?
jQuery的:
jQuery(function($) {
var services = $('.services').offset().top;
var locations = $('.locations').offset().top;
var about = $('.about').offset().top;
var contact = $('.contact').offset().top;
$(window).scroll(function() {
var scrollPos = $(document).scrollTop();
if (scrollPos >= services && scrollPos < locations) {
$('.nav a').removeClass('active');
$('.wsite-nav-2 a').addClass('active');
} else if (scrollPos >= locations && scrollPos < about) {
$('.nav a').removeClass('active');
$('.wsite-nav-3 a').addClass('active');
} else if (scrollPos >= about && scrollPos < contact) {
$('.nav a').removeClass('active');
$('.wsite-nav-4 a').addClass('active');
} else if (scrollPos >= contact) {
$('.nav a').removeClass('active');
$('.wsite-nav-5 a').addClass('active');
} else if (scrollPos <= services) {
$('.nav a').removeClass('active');
$('.wsite-nav-1 a').addClass('active');
}
});
$('.wsite-nav-1 a').addClass('active');
$('.nav a').click(function() {
$('.nav a, .wsite-nav-1 a').removeClass('active');
$(this).addClass('active');
var target = $('.anchor-link').offset().top;
$('html, body').animate({
scrollTop: jQuery( jQuery(this).attr('href') ).offset().top
}, 500);
return false;
});
});
HTML:
<div class="nav">
<ul>
<li class="wsite-nav-1"><a href="#">Home</a></li>
<li class="wsite-nav-2"><a href="#">Services</a></li>
<li class="wsite-nav-3"><a href="#">Locations</a></li>
<li class="wsite-nav-4"><a href="#">About</a></li>
<li class="wsite-nav-5"><a href="#">Contact</a></li>
</ul>
</div>
<div class="content">
<div class="anchor">
<a name="A" class="anchor-link services"></a>
</div>
<div class="anchor">
<a name="B" class="anchor-link locations"></a>
</div>
<div class="anchor">
<a name="C" class="anchor-link about"></a>
</div>
<div class="anchor">
<a name="D" class="anchor-link contact"></a>
</div>
</div>
答案 0 :(得分:0)
您的平滑滚动代码是完美的,除了nav a
链接的href属性都是#
,它们应该是各个部分的id
。我已经更新了我最近的codepen,请检查:) https://codepen.io/bb027/pen/VMQdXL