【问题标题】:is there any way to detect the touching of two dom elements at the same time using js touch events?有没有办法使用js触摸事件同时检测两个dom元素的触摸?
【发布时间】:2018-09-12 23:30:14
【问题描述】:

我正在使用 angular6 创建一个简单的移动应用程序。我的应用程序中有两个按钮,同时单击/点击两个按钮时我需要调用一个函数。经过大量搜索,我找到了js中的触摸事件处理函数。这是我的代码

app.component.ts

  testfunc(event) {
    this.testval = 1;
  }

  testfunc1() {
    this.testval = 2;
  }

  testfunc2(event) {
    event.preventDefault();
    if (this.testval == 1) {
      alert(this.testval);
    }
  }

app.component.html

 <div class="clutchBtn" #clBtn (touchstart)="testfunc($event)"  (touchend)="testfunc1()"></div>
 <div class="gearBtn" #gearBtn (touchstart)="testfunc2($event)"></div>

在上面的代码中,我使用 'touchstart' 和 'touchend' 事件处理程序来检测 dom 元素中触摸事件的进入和离开。如果用户触摸第一个按钮,那么 testfunc() 将被调用,并且值'testVal' 将设置为 1。如果用户的手指从第一个按钮上移开,则 'testVal' 的值设置为 2。然后我在第二个按钮中添加一个 testfun2() 来检测用户是否仍然触摸第一个按钮按钮。问题是触摸事件无法正常工作,即,当我同时按下两个按钮时,将显示警报框,然后当我只按下第二个按钮时它仍然显示。因为 testVal 的值还是 '1'。请问如何解决这个问题?有没有其他好的方法来检测同时点击两个按钮?

【问题讨论】:

    标签: javascript angular6


    【解决方案1】:

    你应该可以查询元素

    @ViewChild('buttonVar') button;
    touchStart1$:Observable<any>;
    

    然后申请注册触摸事件

    ngOnInit() {
      this.touchStart1$ = Observable.fromEvent(this.button.nativeElement, 'touchstart');
    }
    

    对两个按钮都这样做,并使用 RxJS forkJoin 运算符来组合两个可观察对象以等待两个动作被点击。

    编辑: 事实上,不要使用 forkJoin。还有更多要实现的描述。 对于工作示例,请查看此 stackblitz: https://stackblitz.com/edit/angular-5cjt1b

    【讨论】:

    • 您能否发布代码以使用 forkjoin 组合两个可观察对象?
    • this.touch1 = fromEvent(this.clBtnElement.nativeElement, 'touchstart'); this.touch2 = fromEvent(this.gearBtnElement.nativeElement, 'touchstart'); this.joinTest = forkJoin(this.touch1, this.touch2); this.joinTest.subscribe((res) => { console.log(res); });
    • 但是当我按下按钮时它没有在控制台中显示任何内容。
    • 也许您想设置一个 stackblitz 来复制您的问题并从那里开始工作?
    • 请查看以下网址stackblitz.com/edit/angular-b7wj6k
    猜你喜欢
    • 2011-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多