如何使用 JavaScript 来检测 div 在不移动窗口的情况下滚动了多远?



我有一个有效的JavaScript函数,可以检测我滚动到页面的哪个点,导航栏通过更改与我所在的部分匹配的单词的颜色来响应这一点。

从那以后,我添加了一些视差背景,这意味着将所有网站内容包含在<div>中以创建视差效果(不包括导航栏本身)。为了删除右侧的双滚动条,我将 html 和 body 标签设置为overflow: hidden,这对视差非常有用。

但是,我的导航栏不再显示页面上的位置。

我花了很长时间才理论化为什么它停止工作(我只学习了一周的html,css和一些JS,所以我有点慢)。据推测,因为我的内容(包括告诉导航栏何时更改颜色的锚点)都包装在滚动<div>内,所以使用 JS 函数中的$(window)部分是没有用的,因为从技术上讲,窗口是静态的,<div>内容正在滚动。

所以我的问题如下:例如,JS函数是否可以监视锚点何时经过它所包含<div>的顶部?

事后的想法是,因为我对所有这些编码都是新手,而且它仍然有点压倒性,调整我的视差方法是否更实用,这样我就不必将网站内容包含在<div>中?

这是我与我怀疑导致问题的$(window)部分一起使用的 JavaScript:

$(window).on('scroll', function() {
$('.hiddenanchor').each(function() {
if($(window).scrollTop() >= $(this).offset().top 
&& !$('li a').hasClass("clicked")) {
var id = $(this).attr('id');
$('#navheader li a').removeClass('active');
$('#navheader li a[id="link'+ id +'"]').addClass('active');
}
})
});

.hiddenanchor是指定网站的哪个部分是新部分的标记。因此,当该部分位于窗口顶部时,JS 函数会将class="active"添加到匹配的导航栏文本中。

我是 StackOverflow 的新手,所以我不想过度发布 - 希望现在有足够的信息,但如果有人愿意提供帮助需要更多信息,我非常乐意提供任何需要的信息。

感谢任何可能帮助我的人,请记住,我只是一个星期前的代码新手,所以请放轻松!

编辑:为上下文添加一些 html。

<html>
<head>
</head>
<header>
<nav>
<ul>
<div>
<li><a href="#01">Navlink 1</a></li>
<li><a href="#02">Navlink 2</a></li>
<li><a href="#03">Navlink 3</a></li>
</div>
</ul>
</nav>
</header>
<body>
<main class="wrapper">
<section class="content">
<div class="main-div-column">
<a class="anchor" id="01">
</a>
<div class="main-div section-1">
Lots of text <br>
Lots of text <br>
Lots of text <br>
Lots of text <br>
Lots of text <br>
Lots of text <br>
Lots of text <br>
Lots of text <br>
</div>
<a class="anchor" id="02">
</a>
<div class="main-div section-2">
Lots more text <br>
Lots more text <br>
Lots more text <br>
Lots more text <br>
Lots more text <br>
Lots more text <br>
Lots more text <br>
Lots more text <br>
</div>
<a class="anchor" id="03">
</a>
<div class="main-div section-3">
Some more text <br>
Some more text <br>
Some more text <br>
Some more text <br>
Some more text <br>
Some more text <br>
Some more text <br>
Some more text <br>
</div>
</div>
</section>
</main>
</body>
</html>

这就是网站的总体布局 -<a class="anchor" id="number">是我在JavaScript中使用的。因此,当该锚点位于屏幕顶部时,它会向匹配的导航链接添加class="active"

您必须将$(window)更改为滚动$('div'),例如,此示例显示div.ex1 滚动了多少

document.querySelector('.ex1').scrollTop

<!DOCTYPE html>
<html>
<head>
<style>
div.ex1 {
background-color: lightblue;
width: 110px;
height: 110px;
overflow: scroll;
}
</style>
</head>
<body>
<script>
	function myFunction(){
document.querySelector('h2 strong').innerHTML = document.querySelector('.ex1').scrollTop;
}
</script>
<h2>count: <strong></strong></h2>
<div class="ex1" onscroll="myFunction()">Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.</div>
</body>
</html>

相关内容

最新更新