【问题标题】:How can I add a class to an element on hover?如何在悬停时向元素添加类?
【发布时间】:2017-07-26 18:21:45
【问题描述】:

当鼠标悬停在 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


【解决方案1】:

不要弄脏我刚刚编写的简单 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);
  }

}

【讨论】:

  • 我很惊讶这个解决方案没有得到更多的关注......非常好的指令。
  • 优雅且可重复使用 = 支持投票!
  • @AbdulmalekAlbakkar monkeyuser.com/2020/election
【解决方案2】:

你也可以使用类似的东西:

[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'"

【讨论】:

    【解决方案3】:

    简单如下

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

    LIVE DEMO

    【讨论】:

    • 如果您有多个按钮怎么办?您只想更改您悬停的班级,而不是所有班级。有没有办法做到这一点?
    • @mario595 使用span 标记并将其包装在`*ngIf 下。如果您需要更多信息,请告诉我
    • @Aravind 你能举个例子吗?我发现每个按钮都在更改类,而不仅仅是悬停在上面的那个。
    • 你能检查一下演示中的 plunker
    • 完美运行。但是我们需要定义变量 mouseOvered: boolean;在 .ts 文件中。
    【解决方案4】:

    如果您以编程方式设置样式(例如,从组件中的属性)并希望它在悬停时更改,您可以查看this Plunker demo

    它还回答了多个元素必须响应鼠标悬停事件时的问题。

    代码如下:

    @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;
      }
    }
    

    【讨论】:

      【解决方案5】:
      <li *ngFor="let q of questions;let i = index" class="list-group-item"  (mouseenter)="isHover = i" [ngClass]="{'active' : isHover === i}">
                  <h5>Question 1</h5>
                  <p>what is the largest man made structure on the earth ?</p>
              </li>
      

      isHover 和问题是在 .ts 文件中声明的属性。

      【讨论】:

        【解决方案6】:

        我拿了 Davut 的例子,把它改成处理多个类...

        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.update( 'add' );
            }
        
            @HostListener( 'mouseleave' ) onMouseLeave() {
                this.update( 'remove' );
            }
        
            protected update( action: string ): void {
                this.hoverClass.split( ' ' ).forEach( item => this.elementRef.nativeElement.classList[action]( item ) );
            }
        }
        

        【讨论】:

          【解决方案7】:

          @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';
            }
          

          【讨论】:

            【解决方案8】:

            最短的解决方案 - 仅 HTML

            <span #newTask class="btn"
                  [ngClass]="newTask.matches(':hover') ? 'btn-success': 'btn-secondary'"
                  (mouseover)="''" (mouseleave)="''"
            >
              New
            </span>
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2019-02-26
              • 1970-01-01
              • 2013-07-03
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2018-05-24
              相关资源
              最近更新 更多