单击事件在计算机上使用鼠标时工作正常。即使将鼠标按钮放在按钮移动光标上然后释放按钮区域内的鼠标按钮,单击事件也会触发。但是与触摸屏一样,它也不起作用。我知道原因是在触摸屏中,这种拖动被视为滚动。当我没有在按钮上移动太多手指时,就会触发点击事件。因此只能上下移动。我的客户有一个问题,就是他们动了太多的手指,很难获得点击事件。是否可以为仍然可以认为是单击而不滚动的手指设置更大的阈值?
我发现本文是由触摸事件自行处理的,并将其翻译为单击事件。 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();
,它确实解决了问题,但目前看来还没有。
这里是一个很好的解决方案。通过使用touchstart
和touchend
事件,您可以测量两个点之间的距离,并在事件关闭时触发单击事件(以像素为单位)。阅读我的评论。
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) {
// id 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 the fire
// a click event (default is 20 but you can override it throught he 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');
})