无法在 Safari 中设置焦点

gle*_*lez 3 html javascript safari setfocus ios

我试图在打开页面或按下按钮时将焦点设置到特定的编辑字段。以下简单的 HTML/Javascript (Test.html) 适用于 Firefox 和 Chrome,但不适用于 Safari。Safari 将使用清除按钮清除文本并使用查找按钮发布文本,但按下选择按钮时不会选择它。任何帮助,将不胜感激。(iPad 2 上的 iOS 7)

更新——替换为工作代码

<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>
Run Code Online (Sandbox Code Playgroud)

Per*_*ell 6

编辑包括 .focus()

尝试

javascript:document.getElementById('identNum').focus().setSelectionRange(0, 999);
Run Code Online (Sandbox Code Playgroud)

移动设备,尤其是 iOS 可能很有趣select();

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

编辑:关于无需用户交互的输入焦点的注释

由@zappullae 发现

在最新版本的 iOS 中,Apple 似乎需要用户交互才能激活键盘,因此在页面加载时这是不可能的。

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