[使用javascript根据滚动位置更改菜单项

问题描述 投票:0回答:2

使用javascript根据滚动位置更改导航栏中的菜单项。

我已更改点击菜单项。但不知道如何根据滚动位置更改活动菜单项。我尝试获取pageYoffset。这是一个非常漫长的过程,看起来也很重复。这是正确的方法还是有效的方法?

HTML代码:

<nav class="navbar navbar-expand-lg navbar-light">
    <div class="collapse navbar-collapse" id="navbarNav">
        <ul class="navbar-nav">
            <li id="home" class="nav-item active">
                <a class="nav-link" href="#homeSection"><i class="fa fa-home"></i></a>
            </li>
            <li id="about" class="nav-item">
                <a class="nav-link" href="#aboutSection"><i class="fa fa-user"></i></a>
            </li>
            <li id="skill" class="nav-item">
                <a class="nav-link" href="#skillSection"><i class="fa fa-cogs"></i></a>
            </li>
            <li id="work" class="nav-item">
                <a class="nav-link" href="#workSection"><i class="fa fa-eye"></i></a>
            </li>
            <li id="contact" class="nav-item">
                <a class="nav-link" href="#contactSection"><i class="fa fa-envelope"></i></a>
            </li>
        </ul>
    </div>
</nav>

JAVASCRIPT:

let header = document.getElementById("navbarNav");
let btns = header.getElementsByClassName("nav-item");
for (var i = 0; i < btns.length; i++) {
    btns[i].addEventListener("click", function () {
        let current = document.getElementsByClassName("active");
        current[0].className = current[0].className.replace(" active", "");
        this.className += " active";
    });
}
javascript html css uinavigationbar
2个回答
-1
投票

可以使用jquery将代码最小化。但是,如果您想单独使用javascript,则会有更长的代码。在滚动事件期间获取每个部分的scolltop值并分配活动类


0
投票

我在Codepen中创建了一个示例,我认为它描述了您的要求。

在我的示例中,我将导航栏水平放置,但是示例很重要。

基本上,当您浏览各部分时,导航栏将根据客户的滚动条的位置将其更新为活动状态。

https://codepen.io/aks-jacoves/pen/KKdYEPe?editors=1111

$(window).on('scroll', e => {
  $('h2').each(function() {
    if($(this).offset().top - 200 < $(window).scrollTop()) {
      let id = '#' + $(this).text().toLowerCase()
      $('li').removeClass('active')
      $('li' + id).addClass('active')
    }
  })
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

<nav class="navbar fixed-top navbar-expand-lg navbar-dark bg-primary">
    <div class="collapse navbar-collapse" id="navbarNav">
        <ul class="navbar-nav">
            <li id="home" class="nav-item active">
                <a class="nav-link" href="#homeSection"><i class="fa fa-home">Home</i></a>
            </li>
            <li id="about" class="nav-item">
                <a class="nav-link" href="#aboutSection"><i class="fa fa-user">About</i></a>
            </li>
            <li id="skill" class="nav-item">
                <a class="nav-link" href="#skillSection"><i class="fa fa-cogs">Skill</i></a>
            </li>
            <li id="work" class="nav-item">
                <a class="nav-link" href="#workSection"><i class="fa fa-eye"></i></a>
            </li>
            <li id="contact" class="nav-item">
                <a class="nav-link" href="#contactSection"><i class="fa fa-envelope">Contact</i></a>
            </li>
        </ul>
    </div>
</nav>

    <div id="container" style="margin-top:50px;">
      <h2 id="section1">Home</h2>
      <p>In my younger and more vulnerable years my father gave me some advice that I've been turning over in my mind ever since.</p>
      <p>"Whenever you feel like criticizing any one," he told me, "just remember that all the people in this world haven't had the advantages that you've had."</p>
      <p>He didn't say any more, but we've always been unusually communicative in a reserved way, and I understood that he meant a great deal more than that. In consequence, I'm inclined to reserve all judgments, a habit that has opened up many curious natures to me and also made me the victim of not a few veteran bores. The abnormal mind is quick to detect and attach itself to this quality when it appears in a normal person, and so it came about that in college I was unjustly accused of being a politician, because I was privy to the secret griefs of wild, unknown men. Most of the confidences were unsought-frequently I have feigned sleep, preoccupation, or a hostile levity when I realized by some unmistakable sign that an intimate revelation was quivering on the horizon; for the intimate revelations of young men, or at least the terms in which they express them, are usually plagiaristic and marred by obvious suppressions. Reserving judgments is a matter of infinite hope. I am still a little afraid of missing something if I forget that, as my father snobbishly suggested, and I snobbishly repeat, a sense of the fundamental decencies is parcelled out unequally at birth.</p>
      <p>And, after boasting this way of my tolerance, I come to the admission that it has a limit. Conduct may be founded on the hard rock or the wet marshes, but after a certain point I don't care what it's founded on. When I came back from the East last autumn I felt that I wanted the world to be in uniform and at a sort of moral attention forever; I wanted no more riotous excursions with privileged glimpses into the human heart. Only Gatsby, the man who gives his name to this book, was exempt from my reaction-Gatsby, who represented everything for which I have an unaffected scorn. If personality is an unbroken series of successful gestures, then there was something gorgeous about him, some heightened sensitivity to the promises of life, as if he were related to one of those intricate machines that register earthquakes ten thousand miles away. This responsiveness had nothing to do with that flabby impressionability which is dignified under the name of the "creative temperament"-it was an extraordinary gift for hope, a romantic readiness such as I have never found in any other person and which it is not likely I shall ever find again. No-Gatsby turned out all right at the end; it is what preyed on Gatsby, what foul dust floated in the wake of his dreams that temporarily closed out my interest in the abortive sorrows and short-winded elations of men.</p>

      <h2 id="section2">About</h2>

      <p>In my younger and more vulnerable years my father gave me some advice that I've been turning over in my mind ever since.</p>
      <p>"Whenever you feel like criticizing any one," he told me, "just remember that all the people in this world haven't had the advantages that you've had."</p>
      <p>He didn't say any more, but we've always been unusually communicative in a reserved way, and I understood that he meant a great deal more than that. In consequence, I'm inclined to reserve all judgments, a habit that has opened up many curious natures to me and also made me the victim of not a few veteran bores. The abnormal mind is quick to detect and attach itself to this quality when it appears in a normal person, and so it came about that in college I was unjustly accused of being a politician, because I was privy to the secret griefs of wild, unknown men. Most of the confidences were unsought-frequently I have feigned sleep, preoccupation, or a hostile levity when I realized by some unmistakable sign that an intimate revelation was quivering on the horizon; for the intimate revelations of young men, or at least the terms in which they express them, are usually plagiaristic and marred by obvious suppressions. Reserving judgments is a matter of infinite hope. I am still a little afraid of missing something if I forget that, as my father snobbishly suggested, and I snobbishly repeat, a sense of the fundamental decencies is parcelled out unequally at birth.</p>
      <p>And, after boasting this way of my tolerance, I come to the admission that it has a limit. Conduct may be founded on the hard rock or the wet marshes, but after a certain point I don't care what it's founded on. When I came back from the East last autumn I felt that I wanted the world to be in uniform and at a sort of moral attention forever; I wanted no more riotous excursions with privileged glimpses into the human heart. Only Gatsby, the man who gives his name to this book, was exempt from my reaction-Gatsby, who represented everything for which I have an unaffected scorn. If personality is an unbroken series of successful gestures, then there was something gorgeous about him, some heightened sensitivity to the promises of life, as if he were related to one of those intricate machines that register earthquakes ten thousand miles away. This responsiveness had nothing to do with that flabby impressionability which is dignified under the name of the "creative temperament"-it was an extraordinary gift for hope, a romantic readiness such as I have never found in any other person and which it is not likely I shall ever find again. No-Gatsby turned out all right at the end; it is what preyed on Gatsby, what foul dust floated in the wake of his dreams that temporarily closed out my interest in the abortive sorrows and short-winded elations of men.</p>
      
      <h2 id="section3">Skill</h2>

      <p>In my younger and more vulnerable years my father gave me some advice that I've been turning over in my mind ever since.</p>
      <p>"Whenever you feel like criticizing any one," he told me, "just remember that all the people in this world haven't had the advantages that you've had."</p>
      <p>He didn't say any more, but we've always been unusually communicative in a reserved way, and I understood that he meant a great deal more than that. In consequence, I'm inclined to reserve all judgments, a habit that has opened up many curious natures to me and also made me the victim of not a few veteran bores. The abnormal mind is quick to detect and attach itself to this quality when it appears in a normal person, and so it came about that in college I was unjustly accused of being a politician, because I was privy to the secret griefs of wild, unknown men. Most of the confidences were unsought-frequently I have feigned sleep, preoccupation, or a hostile levity when I realized by some unmistakable sign that an intimate revelation was quivering on the horizon; for the intimate revelations of young men, or at least the terms in which they express them, are usually plagiaristic and marred by obvious suppressions. Reserving judgments is a matter of infinite hope. I am still a little afraid of missing something if I forget that, as my father snobbishly suggested, and I snobbishly repeat, a sense of the fundamental decencies is parcelled out unequally at birth.</p>
      <p>And, after boasting this way of my tolerance, I come to the admission that it has a limit. Conduct may be founded on the hard rock or the wet marshes, but after a certain point I don't care what it's founded on. When I came back from the East last autumn I felt that I wanted the world to be in uniform and at a sort of moral attention forever; I wanted no more riotous excursions with privileged glimpses into the human heart. Only Gatsby, the man who gives his name to this book, was exempt from my reaction-Gatsby, who represented everything for which I have an unaffected scorn. If personality is an unbroken series of successful gestures, then there was something gorgeous about him, some heightened sensitivity to the promises of life, as if he were related to one of those intricate machines that register earthquakes ten thousand miles away. This responsiveness had nothing to do with that flabby impressionability which is dignified under the name of the "creative temperament"-it was an extraordinary gift for hope, a romantic readiness such as I have never found in any other person and which it is not likely I shall ever find again. No-Gatsby turned out all right at the end; it is what preyed on Gatsby, what foul dust floated in the wake of his dreams that temporarily closed out my interest in the abortive sorrows and short-winded elations of men.</p>
      
      <h2 id="section4">Contact</h2>

      <p>In my younger and more vulnerable years my father gave me some advice that I've been turning over in my mind ever since.</p>
      <p>"Whenever you feel like criticizing any one," he told me, "just remember that all the people in this world haven't had the advantages that you've had."</p>
      <p>He didn't say any more, but we've always been unusually communicative in a reserved way, and I understood that he meant a great deal more than that. In consequence, I'm inclined to reserve all judgments, a habit that has opened up many curious natures to me and also made me the victim of not a few veteran bores. The abnormal mind is quick to detect and attach itself to this quality when it appears in a normal person, and so it came about that in college I was unjustly accused of being a politician, because I was privy to the secret griefs of wild, unknown men. Most of the confidences were unsought-frequently I have feigned sleep, preoccupation, or a hostile levity when I realized by some unmistakable sign that an intimate revelation was quivering on the horizon; for the intimate revelations of young men, or at least the terms in which they express them, are usually plagiaristic and marred by obvious suppressions. Reserving judgments is a matter of infinite hope. I am still a little afraid of missing something if I forget that, as my father snobbishly suggested, and I snobbishly repeat, a sense of the fundamental decencies is parcelled out unequally at birth.</p>
    </div>

查看这是否是您想要的,如果有任何疑问,请评论。

[注意:使用codepen打开代码,此处导航栏未正确加载

© www.soinside.com 2019 - 2024. All rights reserved.