You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何正确实现countUp.js?三类技术使用问题咨询

使用countUp.js实现计数器的问题解答

现有代码

HTML 文件(index.html)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <link rel="stylesheet"
          href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css"
          integrity="sha384-xOolHFLEh07PJGoPkLv1IbcEPTNtaed2xpHsD9ESMhqIYd0nLMwNLD69Npy4HI+N"
          crossorigin="anonymous">

    <title>Test</title>

</head>
<body>

    <div class="container-fluid">

        <div class="row justify-content-center">
             <div id="test-counter" class="col-8 border">
                0
             </div>
        </div>

    </div>

<!-- - - - - - - - - - - - - - - - - - - >
<     Load the JavaScript Libraries      >
<- - - - - - - - - - - - - - - - - - - -->

<!--  own JavaScript  -->
    <script src="js/countUp.js"></script>

<!-- CountUp.js library -->
    <script
            src="https://cdn.jsdelivr.net/npm/countup@1.8.2/countUp.js"
    ></script>

</body>
</html>

本地 js/countUp.js 文件

const c = new countUp.CountUp('test-counter', 100)
c.start()

咨询问题

  1. 我的文件结构是否正确?即是否应在独立的countUp.js文件中实例化对象c并调用,再将该文件引入到index.html中?
  2. 我是否正确从源导入countUp.js?(我是JavaScript新手)
  3. 我能否直接将GitHub上countUp.js的dist文件内容保存到本地文件后引用?

问题解答

1. 文件结构逻辑可行,但加载顺序错误

你可以把实例化代码放在独立文件中,但必须先加载countUp.js库,再加载自定义JS文件。浏览器按script标签顺序加载执行,当前代码先加载了自定义JS,此时countUp库还未加载,必然会触发CountUp is not defined错误。

修正后的script标签顺序:

<!-- CountUp.js library -->
<script src="https://cdn.jsdelivr.net/npm/countup@1.8.2/countUp.js"></script>

<!-- 自定义JavaScript -->
<script src="js/countUp.js"></script>

2. 导入的版本对应写法有误

你使用的是countUp@1.8.2旧版本,它的全局对象不是countUp.CountUp,而是直接CountUp。因此自定义JS代码需修改为:

const c = new CountUp('test-counter', 100)
c.start()

该版本的CDN链接是有效的,但要注意不同版本的全局对象命名差异。

3. 可以直接保存GitHub上的dist文件到本地引用

完全没问题。将GitHub上dist目录中的countUp.js内容复制到本地指定文件夹(比如js目录,命名为countUp.min.js),然后在HTML中引用本地文件即可:

<script src="js/countUp.min.js"></script>
<script src="js/your-custom-code.js"></script>

需确保库文件在自定义代码之前加载,且本地文件路径与HTML中的引用路径一致。


内容的提问来源于stack exchange,提问作者equanimity

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 09:35:24