简体   繁体   English

将 class 添加到香草 JS 中滚动的特定元素

[英]Add class to specific element on scroll in vanilla JS

I have a page with 4 DIV's, every DIV has the height of 100vh, that's 400vh.我有一个包含 4 个 DIV 的页面,每个 DIV 的高度为 100vh,即 400vh。 I want to add a specific class to every DIV dependent on the scroll from the top of the page.我想根据页面顶部的滚动向每个 DIV 添加特定的 class 。 For example, 0-100vh from the top, class will be added to the first div, the 100-200vh class will be added to the second div (and removed from first), etc. Can someone share a javascript code for this (I don't want to use any library, just vanilla JS)?例如,从顶部开始的 0-100vh,class 将添加到第一个 div,100-200vh class 将添加到第二个 div(并从第一个 div 中删除)等。不想使用任何库,只是香草 JS)? :) :)

I tried to Google for it, but I didn't find anything useful for me, only some jQuery scripts...我试着用谷歌搜索它,但我没有发现任何对我有用的东西,只有一些 jQuery 脚本......

<div></div>
<div></div>
<div></div>
<div></div>

<style>
  div {
   height: 100vh;
  }

  .addThis {
    background-color: red;
  } 

</style>

Just want to add class.addThis to one of div's depend on scrolled from top.只想将 class.addThis 添加到 div 之一,这取决于从顶部滚动。

Using getBoundingClientRect().top if element in viewport specific class adding and when out of viewport it'll remove.使用getBoundingClientRect().top如果在视口特定的 class 添加元素,当超出视口时它将被删除。

 window.onscroll = function() { var elem = document.getElementsByTagName("div"); for(i=0;i<elem.length;i++){ if(elem[i].getBoundingClientRect().top <= 0){ for(j=0;j<elem.length;j++){ elem[j].classList.remove("addThis") } elem[i].classList.add("addThis") } } }
 body{ margin:0 } *{ box-sizing:border-box } div { width:100%; height: 100vh; border-bottom:5px solid; background:grey }.addThis { background-color: red; }
 <div></div> <div></div> <div></div> <div></div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM