当使用带有touchmove和touchend事件的事件监听器时,除非我首先使用event.preventDefault();否则我无法让Chrome for Android承认这些事件.在代码的早期.如果我不想阻止默认滚动功能,我是否可以使用其他解决方法让Chrome for Android承认这些事件?
示例代码:
$(document).ready(function () { // Bind touch event listeners. var elem = $('html').get(0); elem.addEventListener('touchstart', function (e) { console.info('"touchstart" detected. Coordinates - ' + getCoord(e)); }); elem.addEventListener('touchmove', function (e) { console.info('"touchmove" detected. Coordinates - ' + getCoord(e)); }); elem.addEventListener('touchend', function (e) { console.info('"touchend" detected. Coordinates - ' + getCoord(e)); }); function getCoord(e) { var touch = false; if (e.touches.length > 0) { touch = e.touches[0]; } else { touch = e.changedTouches[0]; } if (touch) { return 'x: ' + touch.pageX + ', y: ' + touch.pageY; } }
示例小提琴:http://jsfiddle.net/jQ2VS/1/
最后我找到了解决方案(纯js),即使你可能想用它来滑动:
var swipe = function() { var touchX, touchY, movX, movY, go; function prevent(e){ e.preventDefault(); } function start(e) { go = false; document.addEventListener("touchmove", prevent, false); touchX = e.touches[0].pageX; touchY = e.touches[0].pageY; } function move(e) { movX = e.touches[0].pageX - touchX; movY = e.touches[0].pageY - touchY; if(!go) { (Math.abs(movY) < Math.abs(movX)) ? go = true : stop(e); } else { /* *************** */ // cast your spell /* *************** */ } } function stop(e) { document.removeEventListener("touchmove", prevent, false); } document.addEventListener("touchstart", start, true); document.addEventListener("touchmove", move, true); document.addEventListener("touchend", stop, true); document.addEventListener("touchleave", stop, true); document.addEventListener("touchcancel", stop, true); }
希望这有帮助.
如果Google Chrome 认为用户正在平移/滚动并且您没有通话touchcancel
,touchstart
那么它将在大约200毫秒后触发一个事件event.preventDefault()
.
假设您要拦截水平触摸事件并让垂直触摸事件导致平移/滚动,则解决方法是:
在touchstart
,将坐标存储在变量中,并设置iteration
为0.
对于每个touchmove
事件,设置iteration
为iteration
+1.
当iteration
等于4(只是我发现在我的设置中可靠的"幻数")时,计算x轴和y轴的总触摸偏移增量.编辑:在移动设备上,你只会收到一个没有event.preventDefault()的touchmove
如果x轴偏移> y轴偏移*3,则触发event.preventDefault().(这可以确保手势非常水平)
这方面的缺点是用户只能向左/向右滑动或向上/向下滚动.