Javascript 运行 在具有相同 class 但变量不同的多个 div 中运行

Javascript run function inside multiple divs with the same class but different variables

我正在尝试 运行 在多个容器 div 中使用相同的功能 class 滚动。

我需要为每个容器计算不同的值并将它们用于该特定函数。问题是我需要使用 classes 并且我不知道每个页面将有多少个容器。

这是我的 html:

   <div class="div-container container">
      <div class="div-inside"></div>
      <div class="div-inside-2"></div>
      <div class="div-inside"></div>
      <div class="div-inside-2"></div>
   </div>
    

   <div class="div-container container">
      <div class="div-inside"></div>
      <div class="div-inside-2"></div>
      <div class="div-inside"></div>
      <div class="div-inside-2"></div>
   </div>

    
   <div class="div-container container">
      <div class="div-inside"></div>
      <div class="div-inside-2"></div>
      <div class="div-inside"></div>
      <div class="div-inside-2"></div>
   </div>

这就是我正在尝试的

var p1 = document.getElementsByClassName('div-inside')

    function moveDivinside() {

      const divcont = document.querySelectorAll('.div-container')
      divcont.forEach(element => {

        let marginWintop = element.getBoundingClientRect().top; 
        let winHeight = window.innerHeight;
        let difference = winHeight - (winHeight - marginWintop);

                let p1n;
                for (p1n = 0; p1n < p1.length; p1n++) {
                    p1[p1n].style.top = difference * .09 + 'px';
                }
        });
    }
    window.addEventListener('scroll', function () {
            requestAnimationFrame(moveDivinside)
    }, false) 

它似乎只从最后一个容器中获取数据。

您需要稍微更改一下代码:

// this line needs to go: 
// var p1 = document.getElementsByClassName('div-inside')
function moveDivinside() {
  const divcont = document.querySelectorAll('.div-container');
  divcont.forEach(element => {
    // you need to select the elements inside the current element
    var p1 = element.getElementsByClassName('div-inside');

    let marginWinTop = element.getBoundingClientRect().top;
    let winHeight = window.innerHeight;
    let difference = winHeight - (winHeight - marginWinTop);

    let p1n;
    for (p1n = 0; p1n < p1.length; p1n++) {
      p1[p1n].style.top = difference * 0.09 + 'px';
    }
  });
}