Javascript:如何添加和删除标记onscroll事件的类

时间:2017-06-13 17:40:21

标签: javascript jquery html css

我对javascript很新,我学到了一些基础知识,但还没有完全掌握它。我试图通过添加一个活动类来改变我右侧导航的颜色,具体取决于我所处的部分。我不太明白如何在传递特定div时将类附加到我的导航项中。任何帮助将不胜感激。我只是在下面放了一些随机代码,所以我可以链接codepen。这比我在这里发布我的整个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/

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

3 个答案:

答案 0 :(得分: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以像素为单位返回我们当前所在页面的下降距离。

答案 1 :(得分:0)

用于在scroll上更改元素的类--jquery:

to makecell
  create-turtles 1
  [ set shape "circle"
    set color green
    set size 20
  ]
  create-turtles 1
  [ set shape "circle"
    set color red
    set size 15
  ]
  create-turtles 1
  [ set shape "circle"
    set color gray
    set size 10
  ]
end

答案 2 :(得分:-1)

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

1)比较偏移

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

2)获取屏幕坐标

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

现在你只需在滚动事件上使用一个钩子来检查位置并知道你在哪里。我的代码片段只考虑向下滚动,我离开了#34;向上滚动&#34;您可以将其作为练习来实施。

&#13;
&#13;
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++;
  }
  
});
&#13;
h1,h2,h3{
  margin-bottom:20em;
}
h4{
  margin-bottom:30em;
}
nav{
  position:fixed;right:20px;top:20px;
  border:2px solid red;padding:5px;
}
&#13;
<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>
&#13;
&#13;
&#13;