如何在鼠标悬停时向元素添加类? [英] How can I add a class to an element on hover?

查看:128
本文介绍了如何在鼠标悬停时向元素添加类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将鼠标悬停在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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆