之前在AngularJS2中一種button切換效果的實(shí)現(xiàn)(二)中實(shí)現(xiàn)了按鈕的切換效果,但是方法比較low,這次我們使用Angular2的指令來實(shí)現(xiàn)。
指令實(shí)現(xiàn)hover效果
import { Directive, ElementRef, HostListener, Input } from '@angular/core';@Directive({ selector: '[myHighlight]'})export class HighlightDirective { constructor(private el: ElementRef) { } @HostListener('mouseenter') onMouseEnter() { this.highlight('red'); } @HostListener('mouseleave') onMouseLeave() { this.highlight(null); } private highlight(color: string) { this.el.nativeElement.style.backgroundColor = color; }}<button myHighlight class="btn">按鈕一</button><button myHighlight class="btn">按鈕二</button><button myHighlight class="btn">按鈕三</button>
.btn{ height: 50px; width: 100px; background-color: #3399ff; color: white; border: 0; outline: 0; cursor: hand;}hover的效果直接參考Angular官網(wǎng)的代碼。
指令實(shí)現(xiàn)click效果
import { Directive, ElementRef, HostListener, Input } from '@angular/core';@Directive({ selector: '[myHighlight]'})export class HighlightDirective { constructor(private el: ElementRef) { } @HostListener('click') onMouseClick() { this.clickhighlight("black"); } private clickhighlight(color: string) { let obj = this.el.nativeElement; let btns = obj.parentNode.children; //背景色全部重置 for(let i=0; i<btns.length; i++){ btns[i].style.backgroundColor = "#3399ff"; } //設(shè)置當(dāng)前點(diǎn)擊對象的背景色 obj.style.backgroundColor = color; }}<div><button myHighlight class="btn">按鈕一</button><button myHighlight class="btn">按鈕二</button><button myHighlight class="btn">按鈕三</button></div>
.btn{ height: 50px; width: 100px; background-color: #3399ff; color: white; border: 0; outline: 0; cursor: hand;}click效果仍然用@HostListener裝飾器引用屬性型指令的宿主元素,首先把所有button的背景顏色重置,然后再設(shè)置當(dāng)前點(diǎn)擊對象的背景顏色,這樣就達(dá)到了點(diǎn)擊后背景顏色變化的效果。
指令實(shí)現(xiàn)click加hover效果
import { Directive, ElementRef, HostListener, Input } from '@angular/core';@Directive({ selector: '[myHighlight]'})export class HighlightDirective { constructor(private el: ElementRef) { } @HostListener('click') onMouseClick() { this.clickhighlight("black"); } private clickhighlight(color: string) { let obj = this.el.nativeElement; let btns = obj.parentNode.children; //背景色全部重置 for(let i=0; i<btns.length; i++){ btns[i].style.backgroundColor = "#3399ff"; } //設(shè)置當(dāng)前點(diǎn)擊對象的背景色 obj.style.backgroundColor = color; }}<div><button myHighlight class="btn">按鈕一</button><button myHighlight class="btn">按鈕二</button><button myHighlight class="btn">按鈕三</button></div>
.btn{ height: 50px; width: 100px; background-color: #3399ff; color: white; border: 0; outline: 0; cursor: hand;}.btn:hover{ background: black !important;}配合上文click效果,只要加上一行css代碼就可以實(shí)現(xiàn)click和hover的組合效果,此處務(wù)必使用hover偽類,并用!important來提升樣式的優(yōu)先級,如果用@HostListener裝飾器,mouseenter、mouseleave、click三者會打架:
以上所述是小編給大家介紹的使用AngularJS2中的指令實(shí)現(xiàn)按鈕的切換效果,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時(shí)回復(fù)大家的。在此也非常感謝大家對武林網(wǎng)網(wǎng)站的支持!
新聞熱點(diǎn)
疑難解答