ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 자바스크립트를 사용하여 스크롤 위치에 따라 메뉴 항목 변경
    카테고리 없음 2020. 8. 8. 16:43

    질문

    자바스크립트를 사용하여 스크롤 위치에 따라 탐색 모음의 메뉴 항목을 변경합니다.

    클릭시 메뉴 항목을 변경했습니다. 그러나 스크롤 위치에 따라 활성 메뉴 항목을 변경하는 방법을 모릅니다. 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>

    자바스크립트 :

    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";
        });
    }

    답변1

    jquery를 사용하여 코드를 최소화 할 수 있습니다. 하지만 자바스크립트 만 사용하려면 코드가 조금 더 길어질 것입니다. 스크롤 이벤트 중 각 섹션의 scolltop 값을 가져오고 활성 class를 할당합니다.



    답변2

    나는 당신이 요청한 것을 설명하는 코드 펜 예제를 만들었습니다.

    내 예에서는 내비게이션 막대를 가로로 두었지만 예가 중요합니다.

    기본적으로 섹션을 아래로 내려 가면 내비게이션 바는 클라이언트의 스크롤 바 위치에 따라 항목을 활성으로 업데이트합니다.

    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://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.4.1/css/bootstrap.min.css">
    
    <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>

    이것이 당신이 원하는 것인지 확인하고 질문이 있으면 의견을 말하십시오.

    참고 : 코드 펜을 사용하여 코드를 엽니 다. 여기에서 탐색 메뉴가 제대로로드되지 않습니다.



     

     

     

     

    출처 : https://stackoverflow.com/questions/62018088/change-menuitem-based-on-scroll-position-using-javascript

    댓글

Designed by Tistory.