IOS fastclick 获取焦点点击失效,需要多次点击

因为在开发h5页面的时候在ios手机会有300ms的延迟,所以用到了fastclick.js
按照官方的说明,直接引用,如下

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();
        }
    };

最后,把这段代码copy,放到自己项目的配置文件中,这里我用的是Vue,所以把这段代码放在main.js中
在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值