iOS設備input不能自動focus聚焦的解決方法
- 2019 年 11 月 29 日
- 筆記
移動端(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 }
聲明:本文由w3h5原創,轉載請註明出處:《iOS設備input不能自動focus聚焦的解決方法》 https://www.w3h5.com/post/449.html