我一直在为一个网页的计数器工作,我一直被这个我无法解决的功能所困扰.

我有一个4个div的计数器,其中两个是小数字,另外两个是大数字,第一个运行得太快了,我看不到它们的函数.

有人知道如何设置js函数,以便能够以不同的速度运行,并同时完成?

let section_counter = document.querySelector('#section_counter');
let counters = document.querySelectorAll('.counter-item .counter');

// Scroll Animation

let CounterObserver = new IntersectionObserver(
  (entries, observer) => {
    let [entry] = entries;
    if (!entry.isIntersecting) return;

    let speed = 1000;
    counters.forEach((counter, index) => {
      function UpdateCounter() {
        const targetNumber = +counter.dataset.target;
        const initialNumber = +counter.innerText;
        const incPerCount = targetNumber / speed;
        if (initialNumber < targetNumber) {
          counter.innerText = Math.ceil(initialNumber + incPerCount);
          setTimeout(UpdateCounter, 50);
        }
      }
        
      UpdateCounter();

      if (counter.parentElement.style.animation) {
        counter.parentElement.style.animation = '';
      } else {
        counter.parentElement.style.animation = `slide-up 0.3s ease forwards ${
          index / counters.length + 0.5
        }s`;
      }
    
    });
    observer.unobserve(section_counter);
  },
  {
    root: null,
    threshold: window.innerWidth > 768 ? 0.4 : 0.3,
  }
);

CounterObserver.observe(section_counter);
    <section id="section_counter">
      <div class="container">
        <h1 class="section-heading">For every set, you purchase of our sustainable wear, you are helping the world save: </h1>
      </div>
      <div class="container">
        <div class="counter-grid">
            
          <div class="counter-item">
            <h1 class="counter" data-target="15">0</h1>
            <h2 class="counter-heading">Plastic bottles</h2>
            <div class="counter-text">Which takes up to 150 years to decompose</div>
          </div>
          <div class="counter-item">
            <h1 class="counter" data-target="22">0</h1>
            <h2 class="counter-heading">KW of energy</h2>
            <div class="counter-text">Equivalent to 1-day household consumption</div>
          </div>
          <div class="counter-item">
            <h1 class="counter" data-target="5900">0</h1>
            <h2 class="counter-heading">Liters of water</h2>
            <div class="counter-text">Equivalent to the daily consumption of 16 persons (Mexico average)</div>

          </div>
          <div class="counter-item">
          <h1 class="counter" data-target="9000">0</h1>
          <h2 class="counter-heading">Grams of Co2 emissions</h2>
          <div class="counter-text">Equivalent to a 90 km car consumption</div>

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

推荐答案

使用附加属性data-counttry 此解决方案.逻辑很简单:我们将十进制值存储在data-count中,只在里面放一个整数,最后go 掉data-count.

let section_counter = document.querySelector('#section_counter');
let counters = document.querySelectorAll('.counter-item .counter');

// Scroll Animation

let CounterObserver = new IntersectionObserver(
  (entries, observer) => {
    let [entry] = entries;
    if (!entry.isIntersecting) return;

    let speed = 1000;
    counters.forEach((counter, index) => {
      const targetNumber = +counter.dataset.target;
      // Find the unit for one counter step
      const count = targetNumber / speed;
      // Set data attribute for accurate calculation with decimal
      counter.setAttribute('data-count', 0);

      function UpdateCounter() {
        const initialNumber = +counter.innerText;
        // Get decimal number to calculate
        const countNumber = +counter.dataset.count;
        // Getting an integer value with Math.floor()
        const integer = Math.floor(countNumber);
        if (initialNumber < targetNumber) {
          // Set decimal number / toFixed() with speed length, to increase accuracy
          counter.setAttribute('data-count', (countNumber + count).toFixed(`${speed}`.length));
          // Set integer number
          counter.innerText = integer;
          setTimeout(UpdateCounter, 50);
        } else {
          // remove additional data attribute
          counter.removeAttribute('data-count');
        }
      }

      UpdateCounter();

      if (counter.parentElement.style.animation) {
        counter.parentElement.style.animation = '';
      } else {
        counter.parentElement.style.animation = `slide-up 0.3s ease forwards ${
            index / counters.length + 0.5
          }s`;
      }
    });
    observer.unobserve(section_counter);
  }, {
    root: null,
    threshold: window.innerWidth > 768 ? 0.4 : 0.3,
  }
);

CounterObserver.observe(section_counter);
<section id="section_counter">
  <div class="container">
    <h1 class="section-heading">
      For every set, you purchase of our sustainable wear, you are helping the world save:
    </h1>
  </div>
  <div class="container">
    <div class="counter-grid">
      <div class="counter-item">
        <h1 class="counter" data-target="15">0</h1>
        <h2 class="counter-heading">Plastic bottles</h2>
        <div class="counter-text">Which takes up to 150 years to decompose</div>
      </div>
      <div class="counter-item">
        <h1 class="counter" data-target="22">0</h1>
        <h2 class="counter-heading">KW of energy</h2>
        <div class="counter-text">Equivalent to 1-day household consumption</div>
      </div>
      <div class="counter-item">
        <h1 class="counter" data-target="5900">0</h1>
        <h2 class="counter-heading">Liters of water</h2>
        <div class="counter-text">
          Equivalent to the daily consumption of 16 persons (Mexico average)
        </div>
      </div>
      <div class="counter-item">
        <h1 class="counter" data-target="9000">0</h1>
        <h2 class="counter-heading">Grams of Co2 emissions</h2>
        <div class="counter-text">Equivalent to a 90 km car consumption</div>
      </div>
    </div>
  </div>
</section>

Javascript相关问答推荐

有条件的悲剧

当在select中 Select 选项时,我必须禁用不匹配的 Select

从实时数据库(Firebase)上的子类别读取数据

node TS:JWT令牌签名以验证客户端和后台问题之间的身份验证

了解Node.js中的EventEums和浏览器中的addEventEums之间的关系

Angular:动画不启动

我们如何从一个行动中分派行动

当点击注册页面上的注册按钮时,邮箱重复

Rxjs流中生成IMMER不能在对象上操作

TypeError:无法读取未定义的属性(正在读取';宽度';)

WebSocketException:远程方在未完成关闭握手的情况下关闭了WebSocket连接.&#三十九岁;

输入的值的类型脚本array.排序()

ngOnChanges仅在第二次调用时才触发

是否可以在不更改组件标识的情况下换出Reaction组件定义(以维护状态/引用等)?如果是这样的话,是如何做到的呢?

JavaScript -复制到剪贴板在Windows计算机上无效

为什么我的Navbar.css没有显示在本地主机页面上?

在ChartJS中使用spanGaps时,是否获取空值的坐标?

为什么当雪碧的S在另一个函数中时,Phaser不能加载它?

如何向内部有文本输入字段的HTML表添加行?

JSON Web令牌(JWT)错误:RSA密钥对的签名无效