2017-03-06 99 views
8

如何在div上懸停時將類添加到div。如何將一個類添加到懸停的元素上?

模板 -

<div class="red">On hover add class ".yellow"</div> 

組件 -

import {Component} from 'angular2/core'; 

@Component({ 
    selector: 'hello-world', 
    templateUrl: 'src/hello_world.html', 
    styles: [` 
    .red { 
     background: red; 
    } 

    .yellow { 
     background: yellow; 
    } 

    `] 
}) 
export class HelloWorld { 
} 

Demo

[注意 - 我特別想添加一個新的類,而不是修改現有的類]

嘆息!這是一個正常的用例,我還沒有看到任何直接的解決方案!

+0

用指令。閱讀這篇文章,你應該能夠找出其餘的:) https://angular.io/docs/ts/latest/guide/attribute-directives.html –

+1

任何不使用CSS':hover'的理由這個? –

回答

18

你也可以使用類似。

[ngClass]="color" (mouseover)="changeStyle($event)" (mouseout)="changeStyle($event)" 

然後在

color:string = 'red'; 

changeStyle($event){ 
    this.color = $event.type == 'mouseover' ? 'yellow' : 'red'; 
} 

Plunker

+0

這個工程,但有沒有在模板本身的任何簡單的方法,而不是從模板 - >組件 - >模板 – Ajey

+2

其實ya, - '[ngClass] =「顏色「(mouseover)=」color ='yellow'「(mouseout)=」color ='red'「'作品我想 – Dylan

+0

如果您將標記解決方案放入您的答案,我會很高興得到upvote。 – isherwood

5

簡單,如下

<button [class.btn-success]="mouseOvered" 
    (mouseover)="mouseOvered=true" 
    (mouseout)="mouseOvered=false"> Hover me </button> 

LIVE DEMO

+1

如果您有多個按鈕,該怎麼辦?你只想改變你正在懸停的那個類,而不是所有的類。有沒有辦法實現這一點? – mario595

+0

@ mario595使用'span'標籤並將其包裝在'* ngIf下。如果你需要更多的信息,讓我知道 – Aravind

0

如果你設置的樣式編程方式(例如,從組件中的屬性),並希望它改變懸停的組件,你可以有看看this Plunker demo

它還回答了多個元素必須響應mouseover事件時的問題。

下面是代碼:

@Component({ 
    selector: 'app', 
    template: ` 
    <div id="1" 
     (mouseover)="showDivWithHoverStyles(1)" 
     (mouseout)="showAllDivsWithDefaultStyles()" 
     [ngStyle]="hoveredDivId ===1 ? hoveredDivStyles : defaultDivStyles"> 
     The first div 
    </div> 

    <div id="2" 
     (mouseover)="showDivWithHoverStyles(2)" 
     (mouseout)="showAllDivsWithDefaultStyles()" 
     [ngStyle]="hoveredDivId === 2 ? hoveredDivStyles : defaultDivStyles"> 
     The second div 
    </div>` 
}) 
class App{ 
    hoveredDivId; 
    defaultDivStyles= {height: '20px', 'background-color': 'white'}; 
    hoveredDivStyles= {height: '50px', 'background-color': 'lightblue'}; 

    showDivWithHoverStyles(divId: number) { 
    this.hoveredDivId = divId; 
    } 

    showAllDivsWithDefaultStyles() { 
    this.hoveredDivId = null; 
    } 
} 
0

@HostListener裝飾也是,如果你是在整個組件施加一個不錯的選擇。

讓HTML,因爲它是在組件添加@HostListener

<div class="red">On hover add class ".yellow"</div> 

    @HostListener('mouseenter') onMouseEnter() { 
    this.elementRef.nativeElement.class = 'red'; 
    } 

    @HostListener('mouseleave') onMouseLeave() { 
    this.elementRef.nativeElement.class = 'yellow'; 
    }