当手指移动一点时,触摸屏上的点击事件无法触发

4
使用电脑鼠标时,单击事件可以正常工作。即使我将鼠标按钮放在按钮上并移动光标,然后在按钮区域内释放鼠标按钮,单击事件也会触发。但是,在触摸屏幕上使用时却不起作用。我知道原因是在触摸屏幕上,这种拖动被视为滚动。只有当我在按钮上不移动手指时,才会触发单击事件。因此,仅仅按下和松开而没有移动手指。我的客户遇到的问题是他们移动手指太多,很难获得单击事件。是否可能设置更大的阈值,以便手指移动多少仍被视为单击而不是滚动?
我找到了这篇文章,其中自己处理了触摸事件并将它们转换为单击事件。 http://phonegap-tips.com/articles/fast-touch-event-handling-eliminate-click-delay.html 我不想走这条路。
您有任何建议如何解决这个问题吗?
以下是有关触摸事件的更多详细信息:https://developer.mozilla.org/en-US/docs/Web/API/Touch_events 查看如何处理单击,其中描述了在触摸屏幕上单击的工作方式。但是我仍然无法使其正常工作。几个月前,我在我的touchmove事件处理程序中添加了evt.preventDefault();,它确实解决了问题,但目前似乎不起作用了。
编辑:2019.11.5
以下是之前有效但现在无效的内容:
html
<body (touchmove)="touchMoveEvent($event)"></body>

TypeScript
touchMoveEvent(ev: Event): void
{
    ev.preventDefault();
}

下面是一个基本的Angular按钮和点击处理程序的示例,如果用户移动手指太多,则无法正常工作。 我没有检查阈值,但我认为它大约在10px-20px左右。

<button (click)="onClickEventHandler($event)">Press button</button>

onClickEventHandler(ev: Event) {
  //do the thing here
}

我使用Chrome的开发者工具切换设备工具栏测试了触摸屏功能。


3
请添加您的代码 - Vo Kim Nguyen
问题解决了吗?如果还没有,请添加代码。 - 0xAnon
不,它还没有解决。等我上电脑后,我会添加一些代码。 - Janne Harju
6个回答

6

这里有一个不错的解决方案。通过使用touchstarttouchend事件,您可以测量两个点之间的距离,并在事件接近(以像素为单位)时触发点击事件。请阅读我的注释。

    class ScrollToClick {
        constructor(elem, maxDistance = 20) {
            this.elem = elem;
            this.start = null;
            this.maxDistance = maxDistance;

            // Bind the touches event to the element
            this.bindTouchEvents();
        }

        bindTouchEvents() {
            this.elem.addEventListener('touchstart', this.onTouchStart.bind(this), false);
            this.elem.addEventListener('touchend', this.onTouchEnd.bind(this), false);
        }

        onTouchStart(e) {
            // hold the touch start position
            this.start = e.touches[0];

            // clear the position after 2000 mil (could be set for less).
            setTimeout(() => { this.start = null; }, 2000);
        }

        onTouchEnd(e) {
            // if the timeout was called, there will be no start position
            if (!this.start) { return; }

            // calculate the distance between start and end position
            const end = e.changedTouches[0],
                dx = Math.pow(this.start.pageX - end.pageX, 2),
                dy = Math.pow(this.start.pageY - end.pageY, 2),
                distance = Math.round(Math.sqrt(dx + dy));

            // if the distance is fairly small, fire
            // a click event. (default is 20 but you can override it through the constructor)
            if (distance <= this.maxDistance) {
                this.elem.click();
            }

            // clear the start position again
            this.start = null;
        }
    }

然后你可以像这样将其与任何元素一起使用:
// use any element you wish (here I'm using the body)
const elem = document.body;

// initialize the class with the given element
new ScrollToClick(elem);

// listen to a click event on this element.
elem.addEventListener('click', (e) => {
    console.log('Clicked');
})

如果我有空闲时间,明天在工作中我会尝试这个。这个会影响子元素吗?例如,如果我在body里面有一个按钮,那么如果我将body作为输入参数传递给这个类,它是否也会影响到按钮呢? - Janne Harju
@JanneHarju 你可以将按钮元素传递给构造函数。 - AfikDeri
我已经用这种解决方案使其工作,但转换为Angular指令。稍后我会粘贴我的解决方案。 - Janne Harju

1

我的最终解决方案在这里。我忘了在文本中提到我正在使用Angular,尽管我放置了标签。

因此,我制作了Angular指令,并采用了AfikDeri的建议,这与指令样式代码非常接近。

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

@Directive({
  selector: '[touchClick]'
})
export class TouchClickDirective implements OnInit {
  @Input() maxDistance = 100;
  @Input() maxTime = 2000;

  @Input() touchClick: boolean;
  start: Touch;
  constructor(private elem: ElementRef) {
    this.start = null;
  }
  ngOnInit(): void {
    // Bind the touches event to the element
    this.bindTouchEvents();
  }
  bindTouchEvents() {
    this.elem.nativeElement.addEventListener('touchstart', this.onTouchStart.bind(this), false);
    this.elem.nativeElement.addEventListener('touchend', this.onTouchEnd.bind(this), false);
  }

  onTouchStart(e: TouchEvent) {
    // hold the touch start position
    this.start = e.touches[0];

    // clear the position after 2000 mil (could be set for less).
    setTimeout(() => {
      this.start = null;
    }, this.maxTime);
  }

  onTouchEnd(e: TouchEvent) {
    // if the timeout was called, there will be no start position
    if (!this.start) {
      return;
    }

    // calculate the distance between start and end position
    const end = e.changedTouches[0],
      dx = Math.pow(this.start.pageX - end.pageX, 2),
      dy = Math.pow(this.start.pageY - end.pageY, 2),
      distance = Math.round(Math.sqrt(dx + dy));

    // if the distance is fairly small, fire
    // a click event. (default is 20 but you can override it through the constructor)
    if (distance <= this.maxDistance) {
      this.elem.nativeElement.click();
    }

    // clear the start position again
    this.start = null;
  }
}

以下是如何使用它的方法

<button mat-flat-button [touchClick] [maxDistance]="100" [maxTime]="300" (click)="doWarning()">
  Generate Warning
</button>

0

我针对这个问题,基于不同事件监听器上设置的外部值状态,想出了一个快速的解决方案。如果moveState变量在touchmove事件中不改变值,则btn click fn将在touchend事件中触发。Touch start始终会重置状态。

const moveState = false;

btn.addEventListener("click", (e) => handleBtnClick(e));
btn.addEventListener("touchstart", (e) => handleBtnTouchStart(e));
btn.addEventListener("touchmove", (e) => handleBtnTouchMove(e));
btn.addEventListener("touchend", (e) => handleBtnClick(e));

function handleHotspotTouchStart(e){
  moveState = false;
}
function handleHotspotTouchMove(e){
  moveState = true;
}
function handleBtnClick(e){
  e.preventDefault;
  if(e.type === 'touchend'){
    if(moveState) return;
  }
  // trigger btn click action for both cursor click and touch if no movement detected
  btnClick();
}

0

补充一下被接受的答案,这是我的React实现:

import React, { useState } from 'react';
import './Button.css';

interface ButtonProps {
  className: string,
  value: string,
  icon?: string,
  onClick: () => void,
  onPointerDown?: () => void,
  onPointerUp?: () => void,
  style?: React.CSSProperties,
}

function Button(props: ButtonProps): JSX.Element {

  const [touchStart, setTouchStart] = useState(null);

  const onTouchStart = (e) => {

    // store the touchStart position
    setTouchStart(e.touches[0]);

    // clear the position after 2000ms
    setTimeout(() => setTouchStart(null), 2000);

  };

  const onTouchEnd = (e) => {

    // if the timeout was called, there will be no touchStart position
    if (!touchStart) return;

    // calculate the distance between touchStart and touchEnd position
    const touchEnd = e.changedTouches[0],
      dx = Math.pow(touchStart.pageX - touchEnd.pageX, 2),
      dy = Math.pow(touchStart.pageY - touchEnd.pageY, 2),
      distance = Math.round(Math.sqrt(dx + dy));

    // if the distance is fairly small, fire a click event.
    if (distance <= 50 && distance > 5) {
      
      props.onClick();

    }

    // clear the start position again
    setTouchStart(null);

  };

  return (
    <button 
      className={`${props.className}`}
      onClick={props.onClick}
      onPointerDown={props.onPointerDown}
      onPointerUp={props.onPointerUp}
      onTouchStart={onTouchStart}
      onTouchEnd={onTouchEnd}
      style={props.style}
    >
      {props.icon ? <img className="button__icon" src={props.icon} alt=""/> : ''}
      {props.value}
    </button>
  );

}

export default Button;

0

这是一个看起来相似的GitHub Issue。我不是JS开发人员,所以不确定,但希望能有所帮助。


0
你可以使用(mousedown)事件而不是(click),这样会起作用。

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