如何在悬停时向元素添加类? [英] How can I add a class to an element on hover?
本文介绍了如何在悬停时向元素添加类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在将鼠标悬停在 div 上时向 div 添加类.
How to add class to a div when hovered on the 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 {
}
[ 注意 - 我特别想添加一个新类而不是修改现有类 ]
[ NOTE - I specifically want to add a new class and not modify the existing classes ]
叹息!这是一个非常正常的用例,我还没有看到任何直接的解决方案!
Sigh! It is such a normal use case and I do not see any straight forward solution yet!
推荐答案
你也可以使用类似的东西:
You can also just use something like:
[ngClass]="color" (mouseover)="changeStyle($event)" (mouseout)="changeStyle($event)"
然后在组件中
color:string = 'red';
changeStyle($event){
this.color = $event.type == 'mouseover' ? 'yellow' : 'red';
}
或者,在标记中执行所有操作:
Alternatively, do everything in the markup:
[ngClass]="color" (mouseover)="color='yellow'" (mouseout)="color='red'"
这篇关于如何在悬停时向元素添加类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文