【问题标题】:Trigger javascript animation with class added on scroll在滚动上添加类触发 javascript 动画
【发布时间】:2022-01-03 21:37:37
【问题描述】:

当用户滚动到页面的该部分时,我想计算一些数字。我有一段 javascript 在用户到达它时将“滚动”类添加到我的元素中。我有一个单独的 javascript 文件,可以为计数设置动画。

数字使用类名“count”正确动画,但是当我将类名“滚动”到 javascript 代码中时,动画不再起作用。我对javascript的理解非常有限,所以我想知道这是否发生了,因为脚本只在页面首次加载时检查页面是否有这些类的组合,这就是为什么在添加“滚动”类时它会错过它们,如果是这样,有没有办法解决它?

这是我的代码:(js-scroll 是当元素在视口中时触发添加“滚动”类的类)

// How long you want the animation to take, in ms
const animationDuration = 2000;
// Calculate how long each ‘frame’ should last if we want to update the animation 60 times per second
const frameDuration = 1000 / 60;
// Use that to calculate how many frames we need to complete the animation
const totalFrames = Math.round( animationDuration / frameDuration );
// An ease-out function that slows the count as it progresses
const easeOutQuad = t => t * ( 2 - t );

// The animation function, which takes an Element
const animateCountUp = el => {
    let frame = 0;
    const countTo = parseInt( el.innerHTML, 10 );
    // Start the animation running 60 times per second
    const counter = setInterval( () => {
        frame++;
        // Calculate our progress as a value between 0 and 1
        // Pass that value to our easing function to get our
        // progress on a curve
        const progress = easeOutQuad( frame / totalFrames );
        // Use the progress value to calculate the current count
        const currentCount = Math.round( countTo * progress );

        // If the current count has changed, update the element
        if ( parseInt( el.innerHTML, 10 ) !== currentCount ) {
            el.innerHTML = currentCount;
        }

        // If we’ve reached our last frame, stop the animation
        if ( frame === totalFrames ) {
            clearInterval( counter );
        }
    }, frameDuration );
};

// Run the animation on all elements with a class of ‘countup’
const countupEls = document.querySelectorAll( '.count' );
    countupEls.forEach( animateCountUp );
<span class="count js-scroll">40</span>

这就是我尝试使用包含的“滚动”类来触发它的方式:

const countupEls = document.querySelectorAll( '.count.scrolled' );

这里是添加“滚动”类的 javascript 文件:

const scrollElements = document.querySelectorAll(".js-scroll");

const elementInView = (el, dividend = 1) => {
  const elementTop = el.getBoundingClientRect().top;

  return (
    elementTop <=
    (window.innerHeight || document.documentElement.clientHeight) / dividend
  );
};

const elementOutofView = (el) => {
  const elementTop = el.getBoundingClientRect().top;

  return (
    elementTop > (window.innerHeight || document.documentElement.clientHeight)
  );
};

const displayScrollElement = (element) => {
  element.classList.add("scrolled");
};

const hideScrollElement = (element) => {
  element.classList.remove("scrolled");
};

const handleScrollAnimation = () => {
  scrollElements.forEach((el) => {
    if (elementInView(el, 1.25)) {
      displayScrollElement(el);
    } else if (elementOutofView(el)) {
      hideScrollElement(el)
    }
  })
}

window.addEventListener('scroll', () => {
  throttle(handleScrollAnimation, 250);
})

//initialize throttleTimer as false
let throttleTimer = false;
 
const throttle = (callback, time) => {
    //don't run the function while throttle timer is true
    if (throttleTimer) return;
     
    //first set throttle timer to true so the function doesn't run
    throttleTimer = true;
     
    setTimeout(() => {
        //call the callback function in the setTimeout and set the throttle timer to false after the indicated time has passed 
        callback();
        throttleTimer = false;
    }, time);
}

谢谢!

【问题讨论】:

  • 你是不是把scrolljs-scroll弄错了?
  • 不 - 如果我不够清楚,我很抱歉 - “js-scroll”是触发类“滚动”的类,当元素进入视口时,使用单独的 javascript 文件添加不包括在这里。因此,一个 javascript 文件(不包括在内)添加“滚动”类,另一个 javascript 文件为计数设置动画(包括在此处)

标签: javascript onscroll


【解决方案1】:

您应该真正编辑您的问题并包含所有相关代码以获得最佳答案。

我不确定你是如何将类添加到元素中的,但听起来这就是你想要改变数字的地方。

目前,animateCountUp 接受一个参数——屏幕上的一个元素:

const animateCountUp = el => {

即上面的el。在您的代码中,您将它们全部选中,然后将 forEach 元素传递给 animateCountUp

countupEls.forEach( animateCountUp );

那里的语法令人困惑(我假设您正在复制和粘贴)但它类似于 go:

const firstElement = countupEls[0]; // Get the first element
animateCountUp(firstElement);

但对于列表中的每个元素。

我的意思是,你说你是include the class name "scrolled" to the javascript code,我猜你的意思是这样的:

firstElement.classList.add("scrolled");

此时您还需要使用相关元素调用animateCountUp

firstElement.classList.add("scrolled");
animateCountUp(firstElement);

【讨论】:

  • 感谢您的反馈!这是我第一次发布问题,因此我对其进行了编辑以包含另一段 Javascript。我可以在这里找到适合我使用的替代解决方案:marioyepes.com/pure-javascript-scroll-counter
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多