Serenader

Learning by sharing

iOS 上的 touch event

如果在 iOS 的 App 里面嵌套一个 webview ,并且 webview 的大小仅为屏幕的一部分,那么就会出现 手指在 webview 滑动时 滑动过快而超出 webview 窗口,这时候如果手机离开屏幕的话 webview 里面的 touchend 事件并不会被触发。代码会永远停留在 touchmove 事件上。
解决方案是在 touchmove 上做个超时自动触发touchend 事件。
但是有个更加神奇的事情是,如果手指停留在 webview 窗口时,此时通过 new TouchEvent('touchend') 是可以手动创建事件的。
但是当手指移出 webview 窗口时,new TouchEvent('touchend') 就会报错:
'[object EventConstructor]' is not a constructor
解决方案是加个兼容:
var event = null;
try {
    event = new TouchEvent('touchend');
} catch (e) {
    event = document.createEvent('Event');
    event.initEvent('touchend', true, true);
}
以上则可以成功地手动创建事件,然后再通过 eventTarget.dispatchEvent(event) 来手动触发该事件。