首页 > 解决方案 > 在 Yii2 上使用 lib CountUp.js

问题描述

如何在 Yii2 中正确使用 CountUp.js 库?我已经添加了它AppAsset并在 View 中正确加载,现在我将分配 lib 的使用和在同一视图中显示的数字

应用资产.php

<?php
namespace app\assets;

use yii\web\AssetBundle;

class AppAsset extends AssetBundle
{
    public $basePath = '@webroot';
    public $baseUrl = '@web';
    public $css = [
        'css/site.css',
        'css/custom-bootstrap.css',
        'css/font-awesome-4.7.0/css/font-awesome.css',          
    ];
    public $js = [
        'js/countup.js',
    ];
    public $depends = [
        'yii\web\YiiAsset',
        'yii\bootstrap\BootstrapAsset',
    ];
}

有人可以给我一个在视图中使用的例子吗?

标签: javascriptyii2

解决方案


如果您使用的是库的 javascript 版本,则countUp.js需要CountUp(target, startVal, endVal, decimals, duration, options)使用配置参数创建一个新实例,然后调用instance.start();以启动计数器。

参数:

  • target= html 元素、输入、svg 文本元素的 id 或先前选择的元素/输入的 var,其中发生计数
  • startVal=您要开始的值
  • endVal=您想要达到的值
  • decimals=(可选)数字中的小数位数,默认为 0
  • duration=(可选)持续时间,以秒为单位,默认为 2
  • options=(可选,见演示)格式化/缓动选项对象

阅读更多

我假设您已经注册了上面的AppAsset类并加载了源库,否则取消注释countUp.js下面视图顶部的 CDN 链接,复制以下视图并运行它

<?php
    use yii\web\View;

    //$this->registerJsFile('//cdn.jsdelivr.net/npm/countup@1.8.2/dist/countUp.min.js');

    $js = <<<JS
    var options = {
      useEasing: true,
      useGrouping: true,
      separator: ',',
      decimal: '.',
    };
    var demo = new CountUp('counter', 0, 5220, 0, 2.5, options);
    if (!demo.error) {
      demo.start();
    } else {
      console.error(demo.error);
    }
JS;
    $this->registerJs($js, View::POS_END);

?>

<div id="counter">

</div>

推荐阅读