应用场景:因为项目用前端混合式开发,在ios手机会有300ms的延迟,所以用到了[fastclick.js](https://github.com/ftlabs/fastclick)。
按照官方的说明,直接引用,如下
if ('addEventListener' in document) {
document.addEventListener('DOMContentLoaded', function() {
FastClick.attach(document.body);
}, false);
}
但是,有一个问题,就是input的焦点很难获取,往往需要多次点击或者双击才能获取到焦点(朋友们可以去试试,真的很难点),最开始以为是获取焦点区域太小导致,后来发现是这个fastclick.js框架的问题。
SO,我们点开源码,找到这一段
/**
* @param {EventTarget|Element} targetElement
*/
FastClick.prototype.focus = function(targetElement) {
var length;
// Issue #160: on iOS 7, some input elements (e.g. date datetime month) throw a vague TypeError on setSelectionRange. These elements don't have an integer value for the selectionStart and selectionEnd properties, but unfortunately that can't be used for detection because accessing the properties also throws a TypeError. Just check the type instead. Filed as Apple bug #15122724.
if (deviceIsIOS && targetElement.setSelectionRange && targetElement.type.indexOf('date') !== 0 && targetElement.type !== 'time' && targetElement.type !== 'month' && targetElement.type !== 'email') {
length = targetElement.value.length;
targetElement.focus();//加入这一句话就OK了
targetElement.setSelectionRange(length, length);
} else {
targetElement.focus();
}
};
这样就解决问题了。