在JavaScript中获取滚动时当前部分的ID

huangapple go评论67阅读模式
英文:

Get the id of current section on scroll in JavaScript

问题

我正在尝试构建一个点导航,即当您单击每个 "div" 时,它会将您带到特定的部分,这部分目前已经实现。

但是,当滚动时,我还需要更改这些 "div" 的当前状态为活动状态。我该怎么做?

有一个关于点导航外观的图片。

在JavaScript中获取滚动时当前部分的ID

我在寻找如何获取每个部分的滚动位置并将它们分配给各个变量,然后运行一些函数。

<div class="dot-navigation">
  <div>
    <a href="#home"></a>
  </div>
  <div>
    <a href="#about"></a>
  </div>
  <div>
    <a href="#services"></a>
  </div>
  <div>
    <a href="#clients"></a>
  </div>
  <div>
    <a href="#reviews"></a>
  </div>
  <div>
    <a href="#contactus"></a>
  </div>
</div>
英文:

I'm trying to build a dot navigation kind of thing, i.e., when you click on each "div" it takes you to the specific section, which is currently implemented.

But, also while scrolling I need to change the current state of this div's to active. How do I do that?

An image on how the dot navigation looks.

在JavaScript中获取滚动时当前部分的ID

I was looking how to get scroll positions of each section and assign them to each variables and run some function.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-html -->

&lt;div class=&quot;dot-navigation&quot;&gt;
  &lt;div&gt;
    &lt;a href=&quot;#home&quot;&gt;&lt;/a&gt;
  &lt;/div&gt;
  &lt;div&gt;
    &lt;a href=&quot;#about&quot;&gt;&lt;/a&gt;
  &lt;/div&gt;
  &lt;div&gt;
    &lt;a href=&quot;#services&quot;&gt;&lt;/a&gt;
  &lt;/div&gt;
  &lt;div&gt;
    &lt;a href=&quot;#clients&quot;&gt;&lt;/a&gt;
  &lt;/div&gt;
  &lt;div&gt;
    &lt;a href=&quot;#reviews&quot;&gt;&lt;/a&gt;
  &lt;/div&gt;
  &lt;div&gt;
    &lt;a href=&quot;#contactus&quot;&gt;&lt;/a&gt;
  &lt;/div&gt;
&lt;/div&gt;

<!-- end snippet -->

答案1

得分: 1

监听滚动事件,找到当前显示的区域,并根据需要突出显示导航元素。

英文:

Listen for scroll events, find the currently displayed region, and highlight the navigation elements as necessary.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

window.addEventListener(&#39;DOMContentLoaded&#39;, updateNav);
window.addEventListener(&#39;scroll&#39;, updateNav);

function updateNav() {
  const currentRegion = [...document.querySelectorAll(&quot;.region:not([id=&#39;&#39;])&quot;)]
    .find(e=&gt;e.getBoundingClientRect().top&gt;=0)
    
  if(currentRegion) {
    window.location.hash = `#${currentRegion.id}`;
    
    [...document.querySelectorAll(`a:not([href=&#39;#${currentRegion.id}&#39;])`)]
      .forEach(a=&gt;a.classList.remove(&#39;red&#39;))
      
    document.querySelector(`a[href=&#39;#${currentRegion.id}&#39;]`)?.classList.add(&#39;red&#39;)
  }
}

<!-- language: lang-css -->

a { text-decoration:none; color: black}
.red { color: red; }
.region { margin-left: 100px; min-height: 500px; }
.dot-navigation { position:fixed }

<!-- language: lang-html -->

&lt;div class=&quot;dot-navigation&quot;&gt;
  &lt;div&gt;&lt;a href=&quot;#home&quot;&gt;o&lt;/a&gt;&lt;/div&gt;
  &lt;div&gt;&lt;a href=&quot;#about&quot;&gt;o&lt;/a&gt;&lt;/div&gt;
  &lt;div&gt;&lt;a href=&quot;#services&quot;&gt;o&lt;/a&gt;&lt;/div&gt;
  &lt;div&gt;&lt;a href=&quot;#clients&quot;&gt;o&lt;/a&gt;&lt;/div&gt;
  &lt;div&gt;&lt;a href=&quot;#reviews&quot;&gt;o&lt;/a&gt;&lt;/div&gt;
  &lt;div&gt;&lt;a href=&quot;#contactus&quot;&gt;o&lt;/a&gt;&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;region&quot; id=&quot;home&quot;&gt;home...&lt;/div&gt;
&lt;div class=&quot;region&quot; id=&quot;about&quot;&gt;about...&lt;/div&gt;
&lt;div class=&quot;region&quot; id=&quot;services&quot;&gt;services...&lt;/div&gt;
&lt;div class=&quot;region&quot; id=&quot;clients&quot;&gt;clients...&lt;/div&gt;
&lt;div class=&quot;region&quot; id=&quot;reviews&quot;&gt;reviews...&lt;/div&gt;
&lt;div class=&quot;region&quot; id=&quot;contactus&quot;&gt;contactus...&lt;/div&gt;

<!-- end snippet -->

答案2

得分: 0

感谢 Angelina 的评论。

我发现这个链接很有用 https://www.youtube.com/watch?v=fAAk9CATILc

let section = document.querySelectorAll("section");
let dotNav = document.querySelectorAll(".dot-navigation div a");

window.onscroll = () => {
    section.forEach((sec) => {
        let top = window.scrollY;
        let offset = sec.offsetTop - 200;
        let height = sec.offsetHeight;
        let id = sec.getAttribute("id");

        if (top >= offset && top < offset + height) {
            dotNav.forEach((dot) => {
                dot.classList.remove("navDot-active");
                document.querySelector(".dot-navigation div a[href*=" + id + "]").classList.add("navDot-active");
            });
        }
    });
};
英文:

Thanks, Angelina for your comment.

I found this to be useful https://www.youtube.com/watch?v=fAAk9CATILc

let section = document.querySelectorAll(&quot;section&quot;);
let dotNav = document.querySelectorAll(&quot;.dot-navigation div a&quot;);

window.onscroll = () =&gt; {
    section.forEach((sec) =&gt; {
        let top = window.scrollY;
        let offset = sec.offsetTop - 200;
        let height = sec.offsetHeight;
        let id = sec.getAttribute(&quot;id&quot;);

        if (top &gt;= offset &amp;&amp; top &lt; offset + height) {
            dotNav.forEach((dot) =&gt; {
                dot.classList.remove(&quot;navDot-active&quot;);
                document.querySelector(&quot;.dot-navigation div a[href*=&quot; + id + &quot;]&quot;).classList.add(&quot;navDot-active&quot;);
            });
        }
    });
};

huangapple
  • 本文由 发表于 2023年2月20日 00:13:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/75501528.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定