css 仅当显示节时,函数才起作用

xytpbqjk  于 2023-04-01  发布在  其他
关注(0)|答案(1)|浏览(60)

我做了一个数字计数器,但有这个计数器的部分只在我的网站的末尾。所以当我到达该部分时,计数已经发生了。我希望这个函数只在我到达该部分时才开始工作。我如何使用javascript或jquery实现这一点?

function animate(obj, initVal, lastVal, duration) {
  let startTime = null;
  let currentTime = Date.now();
  const step = (currentTime) => {
    if (!startTime) {
      startTime = currentTime;
    }

    const progress = Math.min((currentTime - startTime) / duration, 1);
    obj.innerHTML = Math.floor(progress * (lastVal - initVal) + initVal);
    if (progress < 1) {
      window.requestAnimationFrame(step);
    }
  };
  window.requestAnimationFrame(step);
}

let text1 = document.getElementById('0101');
let text2 = document.getElementById('0102');
let text3 = document.getElementById('0103');

const load = () => {

  animate(text1, 0, 100, 3000);
  animate(text2, 0, 300, 3000);
  animate(text3, 0, 100, 3000);

}
.bloco {
  height: 100em;
}

.container {
  background-color: green;
}

.row {
  display: flex;
  justify-content: space-around;
}

p {
  text-align: center;
  color: white;
  font-size: 2em;
}
<body onload="load()">
  <div class="bloco"></div>
  <div class="container">
    <div class="row">
      <div>
        <p id='0101'>0</p>
        <p>Visitas</p>
      </div>
      <div>
        <p id='0102'>0</p>
        <p>Membros</p>
      </div>
      <div>
        <p><span id='0103'>100</span>%</p>
        <p>Satisfação</p>
      </div>
    </div>
  </div>
  <script src="js-anim.js"></script>
</body>
yruzcnhs

yruzcnhs1#

首先:更改这些html标识符。为什么使用数字?
回答这个问题:

<body onload="load()" onscroll="usuarioMoveuScroll()">

let container = document.getElementsByClassName("container")[0];
function usuarioMoveuScroll() {
    const containerHeight = container.getBoundingClientRect().top;
    if (scrollY >= containerHeight) {
        animate(text1, 0, 100, 3000);
        animate(text2, 0, 300, 3000);
        animate(text3, 0, 100, 3000);
    }
}

基本上,这个函数将计算从页面顶部到容器的像素数。使用这个值,它将与实际滚动垂直高度进行比较。每次向下滚动时,垂直滚动高度增加,而顶部的像素数减少。当第一个值大于第二个值时,这意味着滚动已经到达容器,因此它将触发动画功能。
你也可以有一个控制变量:

let alreadyTriggered = false;

你可以修改函数:

function usuarioMoveuScroll(){
    const containerHeight = container.getBoundingClientRect().top;
       if (scrollY >= containerHeight && !alreadyTriggered) {
          animate(text1, 0, 100, 3000);
          animate(text2, 0, 300, 3000);
          animate(text3, 0, 100, 3000);
          alreadyTriggered = true;
       }
}

相关问题