网站首页lua/js

apicloud页面在IOS下点击300ms延时问题的解决

发布时间:2019-07-16 08:10:56编辑:slayer.hover阅读(4336)

        使用apicloud混合开发APP,在IOS上使用时,每次点击都会有300毫秒的延时,相当糟糕的体验。

    经过一番测试,终于消除了。

    首先引入fastclick.js库,git地址:https://github.com/ftlabs/fastclick/blob/master/lib/fastclick.js

    使用很简单,将js文件引入
        

    <script type='application/javascript' src='/path/to/fastclick.js'></script>

    然后执行:

    if ('addEventListener' in document) {
        document.addEventListener('DOMContentLoaded', function() {
            FastClick.attach(document.body);
        }, false);
    }

    好像是快了一些, 但是在点input输入框的时候,感觉不太对,时常点不上去,无论把输入框调到多大,

    都很难聚焦,又经过一番搜索后,找到下面的代码:


    FastClick.prototype.focus = function(targetElement) {
        var length;
        //兼容处理:在iOS7中,有一些元素(如date、datetime、month等)在setSelectionRange会出现TypeError
        //这是因为这些元素并没有selectionStart和selectionEnd的整型数字属性,所以一旦引用就会报错,
        //因此排除这些属性才使用setSelectionRange方法
        if (deviceIsIOS && targetElement.setSelectionRange && targetElement.type.indexOf('date') !== 0 && 
    targetElement.type !== 'time' && targetElement.type !== 'month' && targetElement.type !== 'email') {
            length = targetElement.value.length;
            targetElement.setSelectionRange(length, length);
            /*修复bug ios 11.3不弹出键盘,这里加上聚焦代码,让其强制聚焦弹出键盘*/
            targetElement.focus();
        } else {
            targetElement.focus();
        }
    };


    经过体验,input框是可以聚焦了,但点击输入框后,还是要等候漫长的300ms,input框的焦点才生效。

    这怎么行, 仔细看这段代码,似乎是判断是输入框,再进行聚焦操作,那样的话,直接给input框加点击聚焦操作不就好了。

    var ios = document.getElementsByTagName("input");
         for(var i = 0; i < ios.length; i++){
         ios[i].onclick=function(){
          this.focus();
         }
    }

    经过操作果然流畅了很多,收工。

    --------------------------------------------更新------------------------------------------------------

    引入fastclick.js库之后,执行

    if ('addEventListener' in document) {
        document.addEventListener('DOMContentLoaded', function() {
            FastClick.attach(document.body);
        }, false);
    }
    FastClick.prototype.focus = function(targetElement) {
            targetElement.focus();
    };
    function inputFocus(){
        setTimeout(function () {
            var ios = document.getElementsByTagName("input");
            for(var i = 0; i < ios.length; i++){
                ios[i].onclick=function(){
                    this.focus();
                }
            }
        },50);
    }

    然后在页面里显式调用inputFocus();

    注:如果使用了Vue来绑定过的input框, 需要在input框渲染完成后,再调用inputFocus(),否则无效。

评论