stackblitz
錄了個視頻玩
思路
- 監聽到鼠標按下後發出一個流
- 將這個流轉接到一個定時產出的流,
-
通過監聽這個流得知鼠標按下的時間,
- 當時間到達時取消訂閱。
- 當鼠標擡起時取消訂閱。
實作
-
爲了達成思路,首先需要兩個流:
- 鼠標按下的流:
pushStart$ = new Subject();
- 鼠標擡起的流:
pushOver$ = new Subject();
- 鼠標按下的流:
-
監聽鼠標按下,擡起事件。將上述兩個流產出。
@HostListener('mousedown') @HostListener('touchstart') pushStart() { this.pushStart$.next('start') console.log('start') } @HostListener('mouseup') @HostListener('mouseleave') @HostListener('touchend') pushOver(){ this.pushOver$.next('over') this.rd2.removeClass(this.el.nativeElement,'vibrate-1') }
-
加入監聽流的邏輯,修改pushStart代碼如下:
@HostListener('mousedown') @HostListener('touchstart') pushStart() { this.pushStart$.pipe( tap(()=>{ this.rd2.addClass(this.el.nativeElement,'vibrate-1') }), switchMap(() => interval(1000)), tap(time => console.log(time)), takeUntil(this.pushOver$), filter(time => time === 1), take(1) ).subscribe(() => { console.log('done') this.rd2.removeClass(this.el.nativeElement, 'vibrate-1'); const node = this.rd2.parentNode(this.el.nativeElement) this.rd2.removeChild(node,this.el.nativeElement) this.delete.emit('done') }) this.pushStart$.next('start') console.log('start') }
- 在tap中進行樣式的添加以及控制檯時間的輸出,便於調試。
- takeUntil,filter,take(1),使這段流將在鼠標擡起時取消訂閱,或者在計時到達1時(鼠標按下經過2秒)發出一個1,使觀察者能夠知道按壓時間已到,以便進行樣式,動畫的設置,以及刪除dom元素等操作。