【问题标题】:Angular 2 Hover eventAngular 2 悬停事件
【发布时间】:2016-10-07 19:02:25
【问题描述】:

在新的 Angular2 框架中,有谁知道像事件一样进行悬停的正确方法?

Angular1 中有 ng-Mouseover,但似乎没有被继承。

我浏览了文档并没有找到任何东西。

【问题讨论】:

标签: javascript angular events hover


【解决方案1】:

如果你想在任何 HTML 元素上执行类似悬停的事件,那么你可以这样做。

HTML

 <div (mouseenter) ="mouseEnter('div a') "  (mouseleave) ="mouseLeave('div A')">
        <h2>Div A</h2>
 </div> 
 <div (mouseenter) ="mouseEnter('div b')"  (mouseleave) ="mouseLeave('div B')">
        <h2>Div B</h2>
 </div>

组件

import { Component } from '@angular/core';

@Component({
    moduleId: module.id,
    selector: 'basic-detail',
    templateUrl: 'basic.component.html',
})
export class BasicComponent{

   mouseEnter(div : string){
      console.log("mouse enter : " + div);
   }

   mouseLeave(div : string){
     console.log('mouse leave :' + div);
   }
}

您应该同时使用 mouseentermouseleave 事件,以便在角度 2 中完全实现功能性悬停事件。

【讨论】:

【解决方案2】:

是的,在 angular2 中有 on-mouseover,而不是像 angular 1.x 中的 ng-Mouseover,所以你必须这样写:-

<div on-mouseover='over()' style="height:100px; width:100px; background:#e2e2e2">hello mouseover</div>

over(){
    console.log("Mouseover called");
  }

正如@Gunter 在评论中建议的那样,on-mouseover 的替代品我们也可以使用它。有些人更喜欢 on- 前缀替代方案,称为规范形式。

更新

HTML 代码 -

<div (mouseover)='over()' (mouseout)='out()' style="height:100px; width:100px; background:#e2e2e2">hello mouseover</div>

控制器/.TS 代码 -

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular';

  over(){
    console.log("Mouseover called");
  }

  out(){
    console.log("Mouseout called");
  }
}

Working Example

其他一些鼠标事件可以在 Angular 中使用 -

(mouseenter)="myMethod()"
(mousedown)="myMethod()"
(mouseup)="myMethod()"

【讨论】:

  • 为什么不&lt;div (mouseover)='over()'? ;-)
  • @GünterZöchbauer,他们是所有事件的某种列表吗?我查看了 angular 2 网站,但找不到(鼠标悬停)
  • 这些不是 Angular 事件,而是浏览器事件。
  • 显然是这样,但有没有人有这个 Angular 文档的链接?我觉得它超级抽象和稀疏。我只是在寻找一个随心所欲的列表,所以我知道什么是标准的。
  • @Pardeep Jain,如何在鼠标悬停时添加一个类并在鼠标移出时删除该类?
【解决方案3】:

你可以用主机来做:

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

@Directive({
  selector: '[myHighlight]',
  host: {
    '(mouseenter)': 'onMouseEnter()',
    '(mouseleave)': 'onMouseLeave()'
  }
})
export class HighlightDirective {
  private _defaultColor = 'blue';
  private el: HTMLElement;

  constructor(el: ElementRef) { this.el = el.nativeElement; }

  @Input('myHighlight') highlightColor: string;

  onMouseEnter() { this.highlight(this.highlightColor || this._defaultColor); }
  onMouseLeave() { this.highlight(null); }

   private highlight(color:string) {
    this.el.style.backgroundColor = color;
  }

}

只需将其调整为您的代码(位于:https://angular.io/docs/ts/latest/guide/attribute-directives.html

【讨论】:

    【解决方案4】:

    如果您对鼠标进入或离开您的某个组件感兴趣,您可以使用@HostListener 装饰器:

    import { Component, HostListener, OnInit } from '@angular/core';
    
    @Component({
      selector: 'my-component',
      templateUrl: './my-component.html',
      styleUrls: ['./my-component.scss']
    })
    export class MyComponent implements OnInit {
    
      @HostListener('mouseenter') 
      onMouseEnter() {
        this.highlight('yellow');
      }
    
      @HostListener('mouseleave') 
      onMouseLeave() {
        this.highlight(null);
      }
    
    ...
    
    }
    

    正如@Brandon 对 OP (https://angular.io/docs/ts/latest/guide/attribute-directives.html) 的评论中的链接所述

    【讨论】:

      【解决方案5】:

      只需在 Angular2+ 中执行 (mouseenter) 属性...

      在你的 HTML 中做:

      <div (mouseenter)="mouseHover($event)">Hover!</div> 
      

      在你的组件中做:

      import { Component, OnInit } from '@angular/core';
      
      @Component({
        selector: 'component',
        templateUrl: './component.html',
        styleUrls: ['./component.scss']
      })
      
      export class MyComponent implements OnInit {
      
        mouseHover(e) {
          console.log('hovered', e);
        }
      } 
      

      【讨论】:

        【解决方案6】:

        为了处理过度事件,您可以尝试这样的事情 (对我有用):

        在 Html 模板中:

        <div (mouseenter)="onHovering($event)" (mouseleave)="onUnovering($event)">
          <img src="../../../contents/ctm-icons/alarm.svg" class="centering-me" alt="Alerts" />
        </div>
        

        在角度分量中:

            onHovering(eventObject) {
            console.log("AlertsBtnComponent.onHovering:");
            var regExp = new RegExp(".svg" + "$");
        
            var srcObj = eventObject.target.offsetParent.children["0"];
            if (srcObj.tagName == "IMG") {
                srcObj.setAttribute("src", srcObj.getAttribute("src").replace(regExp, "_h.svg"));       
            }
        
           }
           onUnovering(eventObject) {
            console.log("AlertsBtnComponent.onUnovering:");
            var regExp = new RegExp("_h.svg" + "$");
        
            var srcObj = eventObject.target.offsetParent.children["0"];
            if (srcObj.tagName == "IMG") {
                srcObj.setAttribute("src", srcObj.getAttribute("src").replace(regExp, ".svg"));
            }
        }
        

        【讨论】:

          【解决方案7】:

          如果鼠标悬停在整个组件上是你的选择,你可以直接@hostListener来处理事件来执行鼠标悬停在下面。

            import {HostListener} from '@angular/core';
          
            @HostListener('mouseenter') onMouseEnter() {
              this.hover = true;
              this.elementRef.nativeElement.addClass = 'edit';
            }
          
            @HostListener('mouseleave') onMouseLeave() {
              this.hover = false;
              this.elementRef.nativeElement.addClass = 'un-edit';
            }
          

          它在@angular/core 中可用。我用角度测试了它4.x.x

          【讨论】:

            【解决方案8】:
            @Component({
                selector: 'drag-drop',
                template: `
                    <h1>Drag 'n Drop</h1>
                    <div #container 
                         class="container"
                         (mousemove)="onMouseMove( container)">
                        <div #draggable 
                             class="draggable"
                             (mousedown)="onMouseButton( container)"
                             (mouseup)="onMouseButton( container)">
                        </div>
                    </div>`,
            
            })
            

            http://lishman.io/angular-2-event-binding

            【讨论】:

              【解决方案9】:

              在您的 js/ts 文件中,将悬停的 html

              @Output() elemHovered: EventEmitter<any> = new EventEmitter<any>();
              onHoverEnter(): void {
                  this.elemHovered.emit([`The button was entered!`,this.event]);
              }
              
              onHoverLeave(): void {
                  this.elemHovered.emit([`The button was left!`,this.event])
              }
              

              在将被悬停的 HTML 中

               (mouseenter) = "onHoverEnter()" (mouseleave)="onHoverLeave()"
              

              在将接收悬停信息的 js/ts 文件中

              elemHoveredCatch(d): void {
                  console.log(d)
              }
              

              在与捕获 js/ts 文件相关的 HTML 元素中

              (elemHovered) = "elemHoveredCatch($event)"
              

              【讨论】:

                【解决方案10】:

                如果您只需要悬停效果,请使用Hover.css

                • npm i hover.css
                • 在文件angular.json 属性projects.architect.build.options.styles --> 将这一行添加到数组中:node_modules/hover.css/scss/hover.scss

                在您想要效果的元素上使用它们的任何类,即:

                <div *ngFor="let source of sources">
                    <div class="row justify-content-center">
                        <div class="col-12 hvr-glow">
                            <!-- My content -->
                        </div>
                    </div>
                </div>
                

                【讨论】:

                  猜你喜欢
                  • 2017-02-07
                  • 1970-01-01
                  • 1970-01-01
                  • 2020-03-12
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  相关资源
                  最近更新 更多