配置資源包:
Yii2對於CSS/JS 管理,使用AssetBundle資源包類別。
打開backend/assets/AppAsset.php
namespace backendassets; use yiiwebAssetBundle; class AppAsset extends AssetBundle { public $basePath = [email protected]/* */'; public $baseUrl = [email protected]/* */';
//全局CSS public $css = [ 'css/animate.css', 'css/style.min.css', ]; //全局JS public $js = [ 'js/jquery-2.1.1.js' ]; //依赖关系 public $depends = [ 'yiiwebYiiAsset', 'yiiootstrapBootstrapAsset', ]; //定义按需加载JS方法,注意加载顺序在最后 public static function addScript($view, $jsfile) { $view->registerJsFile($jsfile, [AppAsset::className(), 'depends' => 'backendassetsAppAsset']); } //定义按需加载css方法,注意加载顺序在最后 public static function addCss($view, $cssfile) { $view->registerCssFile($cssfile, [AppAsset::className(), 'depends' => 'backendassetsAppAsset']); } }
靜態資源在視圖中載入
1. 視圖(或佈局)使用全域CSS/JS
use yiihelpersHtml; use backendassetsAppAsset; use backendwidgetsAlert; AppAsset::register($this);
2. 3.在視圖中載入單獨的JS
$cssString = ".gray-bg{color:red;}"; $this->registerCss($cssString);
or
<?php$this->registerJs( '$("document").ready(function(){ $("#login-form").validate({ errorElement : "small", errorClass : "error", rules: { "AgNav[nav_cn]": { required: true, }, }, messages:{ "AgNav[nav_cn]" : { required : "此字段不能为空.", }, } }); });' );?>
4.視圖中引入JS/CSS檔案
使用自訂函數
<div id="mybutton">点我弹出OK</div> <?php $this->beginBlock('test') ?> $(function($) { $('#mybutton').click(function() { alert('OK'); }); }); <?php $this->endBlock() ?> <?php $this->registerJs($this->blocks['test'], yiiwebView::POS_END); ?>
public static function addScript($view, $jsfile) { $view->registerJsFile($jsfile, [AppAsset::className(), 'depends' => 'backendassetsAppAsset']); } AppAsset::register($this); //只在该视图中使用非全局的jui AppAsset::addScript($this,[email protected]/* *//js/jquery-ui.custom.min.js'); AppAsset::addCss($this,[email protected]/* *//css/font-awesome/css/font-awesome.min.css');
就是以上是的內容,更多相關內容請關注PHP中文網(www.php.cn)!