Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

js添加事件监听 #90

Open
deepthan opened this issue Sep 10, 2020 · 0 comments
Open

js添加事件监听 #90

deepthan opened this issue Sep 10, 2020 · 0 comments
Labels

Comments

@deepthan
Copy link
Owner

js添加事件监听

1. HostListener监听点击事件

import { HostListener } from "@angular/core";
export class xxx {
    @HostListener('window:click', ['$event.target'])
    onClick(targetElement: string) {
      console.log(`You clicked on`, targetElement);
    }
}

  • click表示我们要处理这个a的点击事件,
  • () 圆括号是说发生此事件时,调用等号后面的表达式或函数。
  • 等号后面的 onClick() 是我们定义在组件中的函数名字。

2. 监听滚动事件

主要用到scroll,有滚动条并且窗口滚动才出发。

import { Subscription, fromEvent,  } from "rxjs";

export class xxx {
    scroll$: Subscription;
    
    constructor() {
        this.scroll$ = fromEvent(window, 'scroll').pipe(
          debounceTime(50)
        ).subscribe((event) => {
           this.onWindowScroll(event);
        });
    }
    
    onWindowScroll(event){
        console.log("event", event);
    }
}

3. 监听窗口大小变化事件

 fromEvent(window, 'resize');

方法2

import { Subject } from "rxjs";
import { debounceTime, throttleTime } from "rxjs/operators";

resizeEvent$: Subject<MouseEvent> = new Subject<MouseEvent>();
@HostListener('window:resize', ['$event'])
onResize(event){
    this.resizeEvent$.next(event);
}

this.resizeEvent$.pipe(throttleTime(500),debounceTime(490)).subscribe(res=>
  console.log()
);

4. 监听右键点击事件

如果是window:contextmenu则是监听window的右键点击事件,若是contextmenu则是监听某个元素(组件)的点击事件

import { HostListener } from "@angular/core";

@HostListener("window:contextmenu", ["$event"])
onLisenerRightClick(event) {
    event.preventDefault();
    this.showRightMenu = false;
}

5. 监听粘贴事件

@HostListener('paste', [])
onPaste() {
    // TODO STH
}
@deepthan deepthan added the event label Sep 10, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant