
之前用三目表達(dá)式和ng-class實(shí)現(xiàn)了按鈕切換效果,似乎達(dá)到了我的預(yù)期,但是我覺得還有改進(jìn)空間,網(wǎng)上找了一些資料,大概還有以下幾種實(shí)現(xiàn)方式:
路由
<button class="btn1" routerLink="component1" routerLinkActive="active" type="submit">btn1</button><button class="btn2" routerLink="component2" routerLinkActive="active" type="submit">btn2</button>
.active { background-color: white;}將button切換的頁(yè)面寫成一個(gè)component,通過routerLink鏈接到對(duì)應(yīng)的component并顯示出來,routerLinkActive來控制路由鏈接激活后button的樣式應(yīng)用的class。
但是這個(gè)有局限性,適合button按下去后,整個(gè)頁(yè)面會(huì)有大幅變化的應(yīng)用場(chǎng)景,那么還有其他方法嗎?答案是肯定的。
[class]與(click)
還是通過ngclass和ngclick配合,不過方法和之前寫的略有不同。
字符串?dāng)?shù)組形式
<button [class]="{true:'btn1',false:'btn2'}[isChange]" (click)="isChange=true">btn1</button><button [class]="{false:'btn1',true:'btn2'}[isChange]" (click)="isChange=false" >btn2</button>.btn1{ width: 120px; height: 43px; border: 1px solid #EEEEEE; background: white; border-bottom: none; text-align: center;}.btn2{ border: 1px solid #EEEEEE; border-top: 2px solid #238FF9; width: 120px; height: 42px; background: white; border-bottom: none; text-align: center;}字符串?dāng)?shù)組形式是針對(duì)class簡(jiǎn)單變化,具有排斥性的變化,true是什么class,false是什么class。若要設(shè)置初識(shí)狀態(tài)的class,可以在component中的構(gòu)造函數(shù)中預(yù)先賦值。
對(duì)象key/value處理
<button [class]="{'one':'btn1','two':'btn2','three':'btn3','four':'btn4'}[isChange]" (click)="isChange='one'">btn1</button> <button [class]="{'one':'btn1','two':'btn2','three':'btn3','four':'btn4'}[isChange]" (click)="isChange='two'">btn2</button> <button [class]="{'one':'btn1','two':'btn2','three':'btn3','four':'btn4'}[isChange]" (click)="isChange='three'">btn3</button> <button [class]="{'one':'btn1','two':'btn2','three':'btn3','four':'btn4'}[isChange]" (click)="isChange='four'">btn4</button>這種方法可以對(duì)多個(gè)對(duì)象賦不同的class。或者可以實(shí)現(xiàn)多個(gè)button互斥性變化:
<button [class]="{'one':'btn1','two':'btn2','three':'btn2','four':'btn2'}[isChange]" (click)="isChange='one'">btn1</button> <button [class]="{'one':'btn2','two':'btn1','three':'btn2','four':'btn2'}[isChange]" (click)="isChange='two'">btn2</button> <button [class]="{'one':'btn2','two':'btn2','three':'btn1','four':'btn2'}[isChange]" (click)="isChange='three'">btn3</button> <button [class]="{'one':'btn2','two':'btn2','three':'btn2','four':'btn1'}[以上所述是小編給大家介紹的AngularJS2中一種button切換效果的實(shí)現(xiàn)方法(二),希望對(duì)大家有所幫助,如果大家有任何疑問請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)武林網(wǎng)網(wǎng)站的支持!
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注