当滚动到该页面上的相应部分时,导航中的各个父菜单项将突出显示。
现在,如果访问者决定单击父菜单项而不是滚动,则父菜单项不会正确突出显示,因为滚动功能会跟随并突出显示上一个父菜单项。
点击$(' .nav a)后如何停止滚动功能?
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');
});
});
&#13;
.active {
background: #f0b823;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<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>
&#13;
答案 0 :(得分:1)
我可能会做这样的事情来快速解决。
var isClicked = false;
$(window).scroll(function() {
if (isClicked) {
return false;
}
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() {
isClicked = true;
$('.nav a, .wsite-nav-1 a').removeClass('active');
$(this).addClass('active');
});
&#13;
这是此问题的可接受解决方案 - https://codepen.io/bb027/pen/VMQdXL