Ionic 3中的touchstart和touchend事件

3

我正在寻找一个在移动应用程序的HTML元素上开始和结束触摸的Ionic 3单独事件处理程序。

我发现许多相关的和已解决的问题,但没有针对Ionic 3的解决方案,目前它似乎只支持“tap、press、pan、swipe、rotate和pinch”(https://ionicframework.com/docs/components/#gestures)。 这些都似乎没有在开始时提供“处理程序”,而只有在结束时才有。我看到他们在那时提供了触摸持续时间(deltaTime)的数据,但那时对我的目的毫无用处。

更具体地说,我想要在屏幕第一次触摸元素时清除相关超时,并查看是否在一定时间内(例如250毫秒)结束对同一特定元素的触摸,以便将其评估为“轻按”。

例如像这样的内容:

JS:

timeout_1 = setTimeout(function() {
    // do something if timeout_1 not cleared by touch start
}, 4000);

touched(event) {
    clearTimeout(timeout_1);
    touching_x = true
    timeout_2 = setTimeout(function() {
        touching_x = false
        // store event details and do other things if timeout_2 not cleared by touch end
    }, 250);
}

touch_ended(event) { 
    if (touching_x==true) {
        clearTimeout(timeout_2);    
        // store event details and do some other things
    }
}

HTML:

<button ion-button type="button" (button_touch_started) = "touched($event)" (button_touch_ended) = "touch_ended($event)">Touch button</button>

高精度(低至毫秒级别)对于触摸起始时间尤为重要。

欢迎提供任何建议。


你是否需要touchstart和touchend事件?如果需要,你需要在哪个元素中使用它们? - Abinesh Joyel
正如所解释的那样,我需要起始和结束。这可以用于任何常规HTML元素,例如按钮,在这种情况下它看起来像这样:<button ion-button type="button" (button_touch_started)="touched()">Touch this button</button>(或者如果是<div>是否有区别?) - gaspar
请检查下面的代码示例 - Abinesh Joyel
1个回答

10

Html 尝试使用div或button

<div style="height:100%;width:100%" (touchstart)="touchstart($event)" (touchend)="touchend($event)">
  </div>
  <button ion-button large primary (touchstart)="touchstart($event);">touchstart</button>
<button ion-button large primary (touchend)="touchend($event);">touchend</button>

Ts

touchstart(event){
    console.log(event);
  }

  touchend(event){
    console.log(event);
  }

1
你是在手机还是浏览器上运行的?触摸事件将在移动设备上工作,在浏览器中切换到移动视图并检查touchstart和touchend是否正常工作,可以查看此demo - Abinesh Joyel
非常感谢您的超快速和完美回复。实际上,我基本上也是这样做的,但是您的回复让我进行了更多的测试,并且我意识到这确实是正确的,但是在我一直测试的浏览器上,这个事件通常不起作用。但是现在我尝试了移动设备模拟(https://developers.google.com/web/tools/chrome-devtools/device-mode/)-它工作得非常好。希望这也能帮助其他人。 - gaspar
针对您上面的评论:是的,我在此期间已经意识到了这一点,因此在您回复之前我已经删除了我的先前评论。但还是谢谢您。 - gaspar
请问您能否扩展一下您的演示,并展示如何使用触摸移动浮动div。我正在尝试移动一个带有id的div,但遇到了困难,谢谢。例如,.clientX未定义。https://stackblitz.com/edit/ionic-k3gbhe?file=pages%2Fhome%2Fhome.html - Meryan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接