如何在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',
];
}
有人能给我一个在视图中使用的例子吗?
如果您使用countUp.js
库的javascript版本,则需要使用配置参数创建CountUp(target, startVal, endVal, decimals, duration, options)
的新实例,然后调用instance.start();
启动计数器。
target
= html元素的id,输入,svg文本元素或先前所选元素/输入的var,其中计数发生startVal
=你想要开始的价值endVal
=你想要达到的价值decimals
=(可选)数字小数位数,默认为0duration
=(可选)持续时间,以秒为单位,默认为2options
=(可选,请参阅演示)格式化/缓动选项对象
我假设你已经注册了上面的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>