[英]How can I use JavaScript to detect how far a div has been scrolled by without the window moving?
我有一个有效的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中使用的内容。 因此,当该锚点位于屏幕顶部时,它将为匹配的navlink添加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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.