[英]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.