【问题标题】:Javascript: how to add and remove class of a tag onscroll eventJavascript:如何添加和删除标签滚动事件的类
【发布时间】:2017-06-13 17:40:21
【问题描述】:

我对 javascript 很陌生,我已经学习了一些基础知识,但还没有完全掌握它。我试图通过根据我所在的部分添加一个活动类来改变我的导航颜色。我不太明白当它通过特定的 div 时,我将如何实现将类附加到我的导航项。任何帮助将不胜感激。我只是在下面放置了一些随机代码,以便我可以链接代码笔。这比我在这里发布我的整个 html/css 代码要容易得多。

HTML

div class="global-container">

<div class="logo">
    <div class="layer2">
    </div>
</div>

<div class="copy">
    <p>&copy; text</p>
</div>

<div class="links">
    <a href="#">
        <img src="">
    </a>
    <br>
    <a href="#">
        <img src="">
    </a>
</div>

<!-- End of Logo !-->

<ul class="sidebar">

    <a href="#section1">
        <div class="item">

        </div>
    </a>
    <a href="#section2" >
        <div class="item">

        </div>
    </a>
    <a href="#section3">
        <div class="item">

        </div>
    </a>
    <a href="#section4" >

        <div class="item"  >

        </div>
    </a>
    <a href="#section5" >
        <div class="item">

        </div>
    </a>


</ul>
<!-- Sidebar!-->

<div class="content-container">
    <div id="section1">

        <div class="inner-container">

            <div class="intro-message center">


                    <h1 class="headline-big center">
                    section1</h1>


                    <h2>
                    text
                    </h2>

                    <p>text</p>

                    <div class="button">
                    <a href="#">text</a>
                    <a href="#">text</a>
                    </div>


                    <h6 class="change">text</h6> 


            </div>  


        </div>  

    <div id="section2">



                <div class="about-message">

                    <div class="left">
                        <h1>
                            Section 1</h1>


                            <p> text
                            <br>
                            <br>

                           text</p>
                    </div>


                </div>  

    </div>







    <div id="section3">

        <div class="inner-container">

            <div class="education-message ">


                    <h1 >
                    section3</h1>



        <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
                    tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
                    quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
                    consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
                    cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
                    proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>










                    </div>  



            </div>  





        </div>  

    </div>



    <div id="section4">

        <div class="inner-container">

            <div class="intro-message center">


                    <h1 class="headline-big center">
                    Section4</h1>



                    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
                    tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
                    quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
                    consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
                    cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
                    proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>




            </div>  





        </div>  




    </div>

    <div id="section5">

        <div class="inner-container">

            <div class="intro-message center">


                    <h1 class="headline-big center">
                    section 5</h1>




                    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
                    tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
                    quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
                    consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
                    cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
                    proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>




            </div>  





        </div>  

CSS - 我想添加到 .item 类

.active {
   background-color: red;
 }

https://codepen.io/anon/pen/BZzbGz

这是一个例子: https://bonhomme.lol/

滚动时右侧的导航线会改变颜色。我想实现这种效果,但颜色会根据我到达的部分 div 而变化。

【问题讨论】:

  • 不要只插入无意义的代码,而是插入最相关的部分。毕竟,这就是支票的用途。
  • 格式化您的代码,删除空格并提供一个最小示例。

标签: javascript jquery html css


【解决方案1】:

首先,我获取导航中项目的滚动位置。然后根据当前滚动位置添加/删除类。看看这个:

Your modified Codepen

 $(document).ready(function() {

     $(document).on("scroll", onScroll);

     function onScroll(event) {
         var scrollPos = $(document).scrollTop();

         $(".sidebar a").each(function() {
             var currDiv = $(this).find("div");;
             var currLink = $(this);
             var refElement = $(currLink.attr("href"));

             if(refElement.position().top <= scrollPos && refElement.position().top + refElement.height() > scrollPos) 
             {
                 $(".sidebar a div").removeClass("active");
                 currDiv.addClass("active");
             } else {
                 currDiv.removeClass("active");
             }
          });
      }
 });

编辑:这是您要求的对我们在 IF 中使用的项目的解释

refElement.position().top 返回该元素距页面顶部的像素数。

refElement.height() 是返回代表元素高度的像素。

scrollPos 以像素为单位返回我们当前在页面上的距离。

【讨论】:

  • 这完全符合我的要求!谢谢你。我想知道你是否可以解释这个函数中的参数。 if(refElement.position().top scrollPos)
  • 当然。请参阅更新的答案。另外,如果这解决了您的问题,请将其标记为正确答案并投票。 :)
【解决方案2】:

用于更改滚动元素的类 - jquery:

 <script>
  if($(document).scrollTop>10){
  $("#myDiv).addClass("active");
 }
 else{
  $("#myDiv").removeClass("active");
 }

【讨论】:

    【解决方案3】:

    您有不同的选择:使用库或自己编写代码。如果选择后者,可以尝试以下方法。

    1) 比较偏移量

    window.scrollY 给出页面的滚动量。 element.offsetTop 为您提供页面上元素的(固定)偏移量。您可以比较这些值以确定当前正在查看的元素。

    2) 获取屏幕坐标

    element.getBoundingClientRect() 为您提供元素的屏幕坐标。您可以使用这些来检查它是否位于页面顶部。

    现在您只需在滚动事件上使用挂钩来检查位置并知道您所在的位置。我的代码 sn-p 只考虑向下滚动,我将“向上滚动”的情况留给您作为练习来实现。

    var headings = [document.querySelector("h1"),document.querySelector("h2"),document.querySelector("h3"),document.querySelector("h4")];
    var nav = document.querySelector("nav span");
    var currentIndex=0;
    
    document.addEventListener("scroll",function(){
      // get the current position of the element
      let currentElPos = headings[currentIndex].getBoundingClientRect().top;
      // if it's near the top border update the navigation
      if (currentElPos < 100){
        // in your case, you would update the class
        nav.innerHTML = headings[currentIndex].innerHTML;
        if (currentIndex+1<headings.length) currentIndex++;
      }
      
    });
    h1,h2,h3{
      margin-bottom:20em;
    }
    h4{
      margin-bottom:30em;
    }
    nav{
      position:fixed;right:20px;top:20px;
      border:2px solid red;padding:5px;
    }
    <nav>You are viewing:<br><span>First heading!</span></nav>
    <h1>First heading!</h1>
    <h2>Second heading!</h2>
    <h3>Third heading!</h3>
    <h4>Fourth heading!</h4>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-25
      • 1970-01-01
      • 1970-01-01
      • 2013-08-01
      • 1970-01-01
      • 2013-02-27
      • 2016-11-29
      • 1970-01-01
      相关资源
      最近更新 更多