您基本上想要做的是检测什么是滑动,什么是点击。
我们可以设定一些条件:
- 轻扫是指您触摸点
p1
,然后将手指移动到点,p2
同时手指仍留在屏幕上,然后松开。
- 单击是指您在同一元素上点击开始点击和结束点击。
因此,如果您存储touchStart
发生地点的坐标,则可以在 处测量差异touchEnd
。如果变化足够大,则认为是滑动,否则认为是点击。
此外,如果您想做得非常整洁,您还可以检测在 a 期间用手指“悬停”在哪个元素上touchMove
,如果您不在开始单击的元素上,您可以运行clickCancel
去除高光等的方法。
// grab an element which you can click just as an example
var clickable = document.getElementById("clickableItem"),
// set up some variables that we need for later
currentElement,
clickedElement;
// set up touchStart event handler
var onTouchStart = function(e) {
// store which element we're currently clicking on
clickedElement = this;
// listen to when the user moves finger
this.addEventListener("touchMove" onTouchMove);
// add listener to when touch end occurs
this.addEventListener("touchEnd", onTouchEnd);
};
// when the user swipes, update element positions to swipe
var onTouchMove = function(e) {
// ... do your scrolling here
// store current element
currentElement = document.elementFromPoint(x, y);
// if the current element is no longer the same as we clicked from the beginning, remove highlight
if(clickedElement !== currentElement) {
removeHighlight(clickedElement);
}
};
// this is what is executed when the user stops the movement
var onTouchEnd = function(e) {
if(clickedElement === currentElement) {
removeHighlight(clickedElement);
// .... execute click action
}
// clean up event listeners
this.removeEventListener("touchMove" onTouchMove);
this.removeEventListener("touchEnd", onTouchEnd);
};
function addHighlight(element) {
element.className = "highlighted";
}
function removeHighlight(element) {
element.className = "";
}
clickable.addEventListener("touchStart", onTouchStart);
然后,您还必须为可滚动元素添加侦听器,但是您不必担心如果手指移动到touchStart
和 之间会发生什么touchEnd
。
var scrollable = document.getElementById("scrollableItem");
// set up touchStart event handler
var onTouchStartScrollable = function(e) {
// listen to when the user moves finger
this.addEventListener("touchMove" onTouchMoveScrollable);
// add listener to when touch end occurs
this.addEventListener("touchEnd", onTouchEndScrollable);
};
// when the user swipes, update element positions to swipe
var onTouchMoveScrollable = function(e) {
// ... do your scrolling here
};
// this is what is executed when the user stops the movement
var onTouchEndScrollable = function(e) {
// clean up event listeners
this.removeEventListener("touchMove" onTouchMoveScrollable);
this.removeEventListener("touchEnd", onTouchEndScrollable);
};
scrollable.addEventListener("touchStart", onTouchStartScrollable);
// 西蒙 A.