简体   繁体   English

当 div 滚动到屏幕时,将 class 添加到 div

[英]Adding a class to a div when the div is on scrolled into the screen

So I am trying to add the fadeInTop class to the div with the class animation. The Javascript is not working correctly...所以我试图将 fadeInTop class 添加到带有 class animation 的 div。Javascript 无法正常工作......

The console returns me this which goes back to that line: document.querySelectorAll(".animated".classList.add(fadeInTop))控制台向我返回返回到该行的信息:document.querySelectorAll(".animated".classList.add(fadeInTop))

Uncaught TypeError: Cannot read properties of undefined (reading 'add')
    at application.js:41:1
    at Array.forEach (<anonymous>)
    at IntersectionObserver.<anonymous> (application.js:39:1)

This is in the application.js file:这是在 application.js 文件中:

import Rails from "@rails/ujs"
import Turbolinks from "turbolinks"
import * as ActiveStorage from "@rails/activestorage"
import "channels"


const observer = new IntersectionObserver(entries => {
  entries.forEach(entry => {
    if(entry.isIntersecting){
      document.querySelectorAll(".animated".classList.add(fadeInTop))
    }
  })
})

observer.observe(document.querySelector(".containerFadeIn"))

This is from the home.html.erb view:这是来自 home.html.erb 的视图:

<main class="home-main">
<%# fist box %>

  <div class="home-text-1 containerFadeIn">
    <div class="row containerFadeIn">
      <div class="col-md-9 d-flex animated">
        <div class="vendo-logo-home">
          <%= image_tag "vendo-logo.png"%>
        </div>
        <div>
          <h1>The Future begins</h1>
          <h1 > with <span class="light-blue"><strong>VENDO</strong></span></h1>
        </div>
      </div>
    </div>
  </div>
</main>

my main goal is to make the text fade into the screen when the text is scrolled into the screen (if i add the fadeInTop class to the the fade in animation works)我的主要目标是当文本滚动到屏幕时使文本淡入屏幕(如果我将 fadeInTop class 添加到 animation 作品中的淡入淡出)

This doesn't look right document.querySelectorAll(".animated".classList.add(fadeInTop))这看起来不对document.querySelectorAll(".animated".classList.add(fadeInTop))

  • If you are calling document.querySelectorAll this should return node list so you need to iterate through all elements like:如果您正在调用document.querySelectorAll这应该返回节点列表,因此您需要遍历所有元素,例如:

document.querySelectorAll(".animated").forEach(element => element.classList.add("fadeInTop"))

Keep in mind that nodelist is not an array but it does accept forEach method.请记住,nodelist 不是数组,但它确实接受 forEach 方法。 You might want to convert that into array like Array.from(document.querySelectorAll(".animated")) and then call forEach method.您可能希望将其转换为Array.from(document.querySelectorAll(".animated"))类的数组,然后调用 forEach 方法。

  • If you have only one element then you can call:如果你只有一个元素,那么你可以调用:

document.querySelector(".animated").classList.add("fadeInTop")

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

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