如何在悬停时向元素添加类?

问题描述 投票:23回答:5

如何在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

[注意 - 我特别想添加一个新类,而不是修改现有的类]

叹!这是一个正常的用例,我还没有看到任何直接的解决方案!

angular angular2-template
5个回答
45
投票

您也可以使用以下内容:

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

然后在组件中

color:string = 'red';

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

Plunker

或者,在标记中执行所有操作:

[ngClass]="color" (mouseover)="color='yellow'" (mouseout)="color='red'"

18
投票

简单如下

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

LIVE DEMO


1
投票

如果您以编程方式设置样式(例如,从组件中的属性)并希望它在悬停时更改,您可以查看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';
  }

0
投票

不要脏代码我刚刚编写简单的hover-class指令。

<span hover-class="btn-primary" class="btn" >Test Me</span>

Running Sample

Code Editor stackblitz

在指令下面,

import { Directive, HostListener, ElementRef, Input } from '@angular/core';

@Directive({
  selector: '[hover-class]'
})
export class HoverClassDirective {

  constructor(public elementRef:ElementRef) { }
  @Input('hover-class') hoverClass:any;  

  @HostListener('mouseenter') onMouseEnter() {
    this.elementRef.nativeElement.classList.add(this.hoverClass);
 }

  @HostListener('mouseleave') onMouseLeave() {
    this.elementRef.nativeElement.classList.remove(this.hoverClass);
  }

}
© www.soinside.com 2019 - 2024. All rights reserved.