我的jQuery行为不端。发生的事情是我只想在点击和滚动后正确显示活动菜单按钮。
以下代码正在运行一点。例如,如果我没有单击按钮并只是滚动,它会在我滚动时突出显示导航栏按钮。但是,当我单击一个按钮使其激活时,滚动时它不起作用。因此,单击操作似乎会禁用滚动。
编辑:我忘记提及的其他事情了。当我滚动到联系人的底部部分时,联系人的导航栏按钮也不会突出显示。当我点击它时突出显示但是正如我上面说的那样,当我点击按钮时它会禁用滚动突出显示
$(document).ready(function() {
$(document).on("scroll", onScroll);
//smoothscroll
$('a[href^="#"]').on('click', function(e) {
e.preventDefault();
$(document).off("scroll");
$('a').each(function() {
$(this).removeClass('rjNavActive');
})
$(this).addClass('rjNavActive');
var target = this.hash,
menu = target;
$target = $(target);
$('html, body').stop().animate({
'scrollTop': $target.offset().top + 2
}, 500, 'swing', function() {
window.location.hash = target;
$(document).on("scroll", onScroll);
});
});
});
function onScroll(event) {
var scrollPos = $(document).scrollTop();
$('.rjNav a').each(function() {
var currLink = $(this);
var refElement = $(currLink.attr("href"));
if (refElement.position().top <= scrollPos && refElement.position().top + refElement.height() > scrollPos) {
$('.rjNav a').removeClass("rjNavActive");
currLink.addClass("rjNavActive");
} else {
currLink.removeClass("rjNavActive");
}
});
}
function onScroll(event) {
var scrollPos = $(document).scrollTop();
$('.rjNav.shrink a').each(function() {
var currLink = $(this);
var refElement = $(currLink.attr("href"));
if (refElement.position().top <= scrollPos && refElement.position().top + refElement.height() > scrollPos) {
$('.rjNav.shrink a').removeClass("rjNavActive");
currLink.addClass("rjNavActive");
} else {
currLink.removeClass("rjNavActive");
}
});
}
&#13;
.rjNavActive {
background-color: #dedede;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<a href="#home" class="rjNavActive fa fa-home" data-scroll> Home</a>
<a href="#about" class="fa fa-info" data-scroll> About Me</a>
<a href="#extra" class="fa fa-info" data-scroll> Extra</a>
<a href="#extra2" class="fa fa-picture-o" data-scroll> Extra2</a>
<a href="#extra3" class="fa fa-twitch" data-scroll> Extra3</a>
<a href="#contact" class="fa fa-envelope-o" data-scroll> Contact</a>
<a href="javascript:void(0);" class="navMob icon" onclick="myFunction()" data-scroll>Logo Name - Menu ☰</a>
&#13;
不知道是什么导致它无法正常工作!