在Yii2上使用lib CountUp.js

问题描述 投票:0回答:1

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

AppAsset.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',
    ];
}

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

javascript yii2
1个回答
1
投票

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

Params:

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

Read More

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

<?php
    use yii\web\View;

    //$this->registerJsFile('//cdn.jsdelivr.net/npm/[email protected]/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>
© www.soinside.com 2019 - 2024. All rights reserved.