滚动时边栏未激活-Jquery



我很难识别代码中的问题,但我已经很接近了,因为侧边栏确实暂时处于活动状态,但在滚动时没有保持活动状态。我希望侧边栏充当ToC,并在滚动各部分时变得活跃。如有任何帮助,我们将不胜感激。感谢您的时间和努力!

以下是现场直播:https://www.matthewahn.xyz/cosmo

HTML

<div id="sidenav">
<ul class="no-bullets">
<li>    <a href="#section-1">Cosmo</a> </li>
<li>    <a href="#section-2">Overview</a> </li>
<li>    <a href="#section-3">Challenge</a> </li>
<li>    <a href="#section-4">How Might We</a> </li>
<li>    <a href="#section-5">Solution</a> </li>
<li>    <a href="#section-6">Project Objective</a> </li>
<li>    <a href="#section-7">Research</a> </li>
<li>    <a href="#section-8">Target Users</a> </li>
<li>    <a href="#section-9">Machine Learning</a> </li>
<li>    <a href="#section-10">Project Design</a> </li>
<li>    <a href="#section-11">User Testing</a> </li>
<li>    <a href="#section-12">Prototype</a> </li>
<li>    <a href="#section-13">Reflections</a> </li>
<li>    <a href="#section-14">Future Improvements</a> </li>
</ul>
</div>

CSS

ul.no-bullets {
list-style-type: none;
}

#sidenav {
right: 0;
top: 50%;
transform: translatey(-50%);
position: fixed;
z-index: 10000;
width: 9.375em;
align-items: center;
background-color: #fff;
border-top-left-radius: 25px;
border-bottom-left-radius: 25px;
-webkit-box-shadow: rgba(0,0,0,0.1) 0 6px 10px;
-moz-box-shadow: rgba(0,0,0,0.1) 0 6px 10px;
box-shadow: rgba(0,0,0,0.1) 0 6px 10px;
padding: 1.5em;
overflow-x: hidden;
}
#sidenav a {

text-align: right;
padding-top: 1.2em;
text-decoration: none;
font-size: 0.9em;
color: #ccc;
display: block;
transition: all 100ms ease-in-out;
}
#sidenav ul li a.active {
color: #FF0000;
}
#sidenav a:hover, 
#sidenav a:focus,  {
color: #000;
}

JS&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('active');
})
$(this).addClass('active');

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();
$('#sidenav a').each(function () {
var currLink = $(this);
var refElement = $(currLink.attr("href"));
if (refElement.position().top <= scrollPos && refElement.position().top + refElement.height() > scrollPos) {
$('#sidenav ul li a').removeClass("active");
currLink.addClass("active");
}
else{
currLink.removeClass("active");
}
});
}

根据我的理解:

在用refElement位置检查滚动位置的行中

if (refElement.position().top <= scrollPos ...etc

你需要做的是检查偏移而不是位置。因为,从链接来看,位置是相对于偏移父级的,而偏移是相对于文档的。

在该站点中,我发现position().top几乎总是返回相同的值。你能用offset替换并检查吗?

最新更新