iOS设备input不能自动focus聚焦的解决方法

移动端(iPhone、iPad)的 Safari 或者微信默认是不支持 autofocus 属性的,并且只有用户主动触发的事件才可以使 focus 一类的方法生效。

并且在 iOS 中使用 position: fixed 会导致 input 输入框的位置出现问题,导致 input 无法点击或者说无法聚焦。

找了几个解决方案,归纳整理一下:

1、stackoverflow作者,尝试过模拟点击,触发点击,直接执行click()……各种各样的事情。

这是目前正在用的解决方法:

$scope.gotoElement = function(eID) {
    // call $anchorScroll()
    $scope.smoothScrollTo(eID).then(function() {
        clickElement('#textarea');
    });          
}

function clickElement(e) {
  $(e).on('touchstart', function() {
    //$(e).val('touchstart');
    $(e).focus();
  });

  $(e).trigger('touchstart');
}

2、我们可以模拟一个 autofocus

HTML:

<input type="text" id="focus" />

JS:

document.addEventListener('touchstart', function (e) {
  document.getElementById('focus').focus();
});

3、尝试用触发 click() 替代 focus( ) :

$(this).next('input').click();

4、设置 CSS 属性,可能是 -webkit-user-select:none 导致,将其删除或着修改一下:

[type = text],textarea {
	-webkit-user-select:text
}


推荐阅读:

Linux下如何重置MySQL密码

html中hr标签的基础知识

JetbrainsCrack-2.7激活补丁更新 亲测激活PhpStorm2018

input[type=file]去掉“未选择任何文件”及样式改进

使用 swiper 轮播插件遇到的问题及解决方法

赞 (1)
分享到: +

评论 沙发

Avatar

换个身份

  • 昵称 (必填)
  • 邮箱 (选填)