Textarea标签失去焦点时隐藏手机键盘

今天在做公司年会的手机端上墙页面,发现在输入完成后,键盘没有自动收起

 

后面发现这种情部只是在iphone下才会产生,原来在点击空白的document处textarea并不能失去焦点,解决方案如下:

//判断是否为iphone

var isIPHONE = navigator.userAgent.toUpperCase().indexOf('IPHONE')!= -1;

//失去焦点的方法

function ObjOnBlur(id,time){

    //判断传参是否正确

    if(typeof id != 'string') throw new Error('参数错误');

    //获取文本域textarea标签

    var obj = document.getElementById(id);

    //延迟时间

    var time = time || 300;

    documentTouchend = function(event){

        // 如果当前点击的元素是不是textarea本身

        if(event.target!= obj){

             //延时隐藏

            setTimeout(function(){

                // textarea会失去焦点

                obj.blur();

                // document移除ontouchend事件

                document.removeEventListener('touchend', documentTouchend,false);

           },time);

        }

    };

    //如果标签存在

    if(obj){

        //添加监听事件focus

        obj.addEventListener('focus', function(){

            //添加监听事件touchend

           document.addEventListener('touchend', documentTouchend,false);

        },false);

    }else{

        throw new Error('没有找到元素');

    }

};

//给元素添加方法

$('textarea').on('blur',function(){

    if(isIPHONE){

        new ObjOnBlur('textarea的ID');

        textarea=null;

    };

 //滚动到底部

 window.scrollTo(0,0);

});

猜你喜欢

转载自blog.csdn.net/weixin_40629244/article/details/86545063