標籤:dex this ext htm port 不能 基於 bsp 操作
jQuery,讓我們對dom的操作更加便捷。由於其易用性和可擴充性,jQuer也迅速風靡全球,各種外掛程式也是目不暇接。
我相信很多人並不能直接遠離jQuery去做前端,因為它太好用了,我們以前做的東西大多基於jQuery和它的外掛程式。而且現在Angular2的組件生態還不是很完善,我們在編寫Angular的時候也許會想要用到jQuery。本篇文章就簡單介紹下在Angular2中使用jQuery
如果你不知道怎麼搭建Angular2開發環境,請參考我之前寫這篇文章:Angular2入門系列教程1-使用Angular-cli搭建Angular2開發環境
環境搭好只後先跑起來,然後我們進行下面步驟
首先在index.html中引用jquery,就像我們以前做的那樣
然後我們編寫我們的app.component.ts
1 import { Component,OnInit} from ‘@angular/core‘; 2 declare var $:any; 3 @Component({ 4 selector: ‘app-root‘, 5 templateUrl: ‘./app.component.html‘, 6 styleUrls: [‘./app.component.css‘] 7 }) 8 export class AppComponent implements OnInit{ 9 ngOnInit()10 {11 $("#title").html("<p>this is a string from jQuery html setting</p>");12 }13 }
首先需要使用declare生命我們的jQuery,使之成為一個可用的變數,然後,我們需要匯入OnInit模組並實現,我們編寫的jquery代碼就在這裡,問中展示了我們向id為title的標籤替換內容,HTML頁面是這樣的
<div id="title" class="title"></div>
然後,接下來的運行效果是這樣的
這就意味著我們可以在Angular2中正常使用jQuery了
接下來做個簡單的jQuery外掛程式使用的例子,首先找一個我們要使用的jQuery外掛程式,我用的是這個,3D視覺圖片
首先在index.html 中引用
然後在我們剛才的app.component.ts中的ngOnInit中寫入以下初始化外掛程式代碼
ngOnInit() { $(".card").faceCursor({}); $("#title").html("<p>this is a string from jQuery html setting</p>"); }
然後我們編寫html
1 <div id="title" class="title">2 </div>3 <div class="container">4 <div class="card">5 <img src="../assets/me.jpg" style="width:100%;" alt="me">6 </div>7 </div>
css
1 .card 2 { 3 background: #fff; 4 box-shadow: 0.5em 0 1.25em #ccc; 5 border-radius: .3em; 6 overflow: hidden; 7 max-width: 20em; 8 height: 450px; 9 margin: 0 auto;10 display: block;11 }12 .title{13 text-align: center;14 }15 .container16 {17 width:100%;18 }
這些工作做了之後,我們運行下,就可以得到以下效果
備忘:需要使用到jQuery的地方都要用declare聲明以下,比如其他組件檔案中。
我覺得看了應該都知道怎麼使用了,如果需要代碼請留言
Angular雜談系列1-如何在Angular2中使用jQuery及其外掛程式