Can't Set Focus in Safari

蹲街弑〆低调 提交于 2019-12-08 09:12:31

问题


I'm trying to set focus to a particular edit field when a page opens or button is pressed. The following simple HTML/Javascript (Test.html) works with Firefox and Chrome but not Safari. Safari will clear the text with the clear button and post it with find button but not select it when the select button is pressed. Any help would be appreciated. (iOS 7 on an iPad 2)

Update -- Replaced with working code

<html>

<head>

<!-- Latest JQuery; Must be loaded before Bootstrap -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>

<!-- Latest compiled and minified Bootstrap CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

</head>


<script>
$(document).ready(function()
{
    var identNum = document.getElementById("identNum");
    identNum.value = "AAAABBBB111"
    identNum.focus();
    identNum.setSelectionRange(0, identNum.value.length);
});
</script>


<body>


<div>
    <form class="form-horizontal" name="myForm" role="form" action="Test" method="post">
        <div class="form-group" align="center">
            <div>
                <label class="control-label">Text:</label>
                <input type="text" id="identNum" name="identNum" size="25" value="" style="text-align:center;'">
            </div>

            <div>
                <button class="btn btn-primary">Find</button>
                <a class="btn" onclick="javascript:document.getElementById('identNum').value=''" >Clear</a>
                <a class="btn" onclick="javascript:document.getElementById('identNum').focus(); document.getElementById('identNum').setSelectionRange(0, identNum.value.length)" >Select</a>
            </div>

        </div>
    </form>
</div>

</body>

</html>

回答1:


EDITED TO INCLUDE .focus()

Try

javascript:document.getElementById('identNum').focus().setSelectionRange(0, 999);

Mobile devices, in particular iOS can be quite funny about select();

https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/setSelectionRange

EDIT: A note on input focus without user interaction

As found by @zappullae

It appears that in recent versions of iOS, Apple require user interaction in order to activate the keyboard, so this will not be possible on page load.

https://medium.com/@brunn/autofocus-in-ios-safari-458215514a5f



来源:https://stackoverflow.com/questions/48547975/cant-set-focus-in-safari

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!