最新文章专题视频专题问答1问答10问答100问答1000问答2000关键字专题1关键字专题50关键字专题500关键字专题1500TAG最新视频文章推荐1 推荐3 推荐5 推荐7 推荐9 推荐11 推荐13 推荐15 推荐17 推荐19 推荐21 推荐23 推荐25 推荐27 推荐29 推荐31 推荐33 推荐35 推荐37视频文章20视频文章30视频文章40视频文章50视频文章60 视频文章70视频文章80视频文章90视频文章100视频文章120视频文章140 视频2关键字专题关键字专题tag2tag3文章专题文章专题2文章索引1文章索引2文章索引3文章索引4文章索引5123456789101112131415文章专题3
当前位置: 首页 - 科技 - 知识百科 - 正文

yii2怎么引入css和js文件

来源:动视网 责编:小采 时间:2020-11-03 18:22:18
文档

yii2怎么引入css和js文件

yii2怎么引入css和js文件:引入方式有多种:1、可以直接在视图页面上引入<php use yii\helpers\Html;><=Html::cssFile('@web/css/index.css')><=Html::jsFile('@web/js/jquery.min.js')>2、
推荐度:
导读yii2怎么引入css和js文件:引入方式有多种:1、可以直接在视图页面上引入<php use yii\helpers\Html;><=Html::cssFile('@web/css/index.css')><=Html::jsFile('@web/js/jquery.min.js')>2、


引入方式有多种:

1、可以直接在视图页面上引入

<?php use yiihelpersHtml;?><?=Html::cssFile('@web/css/index.css')?><?=Html::jsFile('@web/js/jquery.min.js')?>

2、可以直接写原生代码引入,路径是项目目录/web/css 或者/js

<script src="js/nav.js"></script>

3、可以使用assetBundle管理css样式及js脚本

资源包定义:basic/assets/AppAsset.php

<?php
/**
 * @link http://www.yiiframework.com/
 * @copyright Copyright (c) 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 */
 namespace appassets; 
use yiiwebAssetBundle; 
/**
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
 class AppAsset extends AssetBundle{
 public $basePath = '@webroot'; 
 public $baseUrl = '@web'; 
 public $css = [ 
 'css/site.css', 
 'css/base.css'
 ]; 
 public $js = [ 
 'js/sliders.js'
 ]; 
 public $depends = [ //依赖包,没有可以不写
 'yiiwebYiiAsset', 
 'yiiootstrapBootstrapAsset', 
 ]; 
 //定义按需加载JS方法,注意加载顺序在最后 
 public static function addScript($view, $jsfile) { 
 $view->registerJsFile($jsfile, [AppAsset::className(), 'depends' => 'apiassetsAppAsset']); 
 } 
 
 //定义按需加载css方法,注意加载顺序在最后 
 public static function addCss($view, $cssfile) { 
 $view->registerCssFile($cssfile, [AppAsset::className(), 'depends' => 'apiassetsAppAsset']); 
 } 
}

在视图文件开头写入:

<?php
use yiihelpersHtml;use appassetsAppAsset;
AppAsset::register($this); 
?>

到现在为止,我们可以在浏览器上测试,发现并没有引入css和js文件,这里要注意了,我们还需要最后一步:

在视图文件中我们要加入一下代码(注:如果我们使用公共视图文件,可以加入到公共视图文件,如果没有使用,可以放到单独页面中)

<?php$this->beginPage() ?> 
<?php $this->head() ?>
<?php $this->beginBody() ?> 
<?php $this->endBody() ?>
<?php $this->endPage() ?>

4、不需要在资源包管理器中定义方法,只要在视图页面中直接引入即可

AppAsset::register($this); 
//css定义一样 
$this->registerCssFile('@web/css/font-awesome.min.css',['depends'=>['apiassetsAppAsset']]); 
 
 $this->registerJsFile('@web/js/jquery-ui.custom.min.js',['depends'=>['apiassetsAppAsset']]); 
//$this->registerJsFile('@web/js/jquery-ui.custom.min.js',['depends'=>['apiassetsAppAsset'],
'position'=>$this::POS_HEAD]);

相关文章教程推荐:yii教程

文档

yii2怎么引入css和js文件

yii2怎么引入css和js文件:引入方式有多种:1、可以直接在视图页面上引入<php use yii\helpers\Html;><=Html::cssFile('@web/css/index.css')><=Html::jsFile('@web/js/jquery.min.js')>2、
推荐度:
标签: 文件 js css
  • 热门焦点

最新推荐

猜你喜欢

热门推荐

专题
Top