簡體   English   中英

無法在Safari中設置焦點

[英]Can't Set Focus in Safari

當頁面打開或按下按鈕時,我試圖將焦點設置到特定的編輯字段。 以下簡單的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>

編輯包括.focus()

嘗試

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

移動設備(尤其是iOS select();select();可能會很有趣select();

https://developer.mozilla.org/zh-CN/docs/Web/API/HTMLInputElement/setSelectionRange

編輯:關於輸入焦點的注釋,無需用戶交互

如@zappullae所發現

看來,在最新版本的iOS中,Apple需要用戶交互才能激活鍵盤,因此在頁面加載時將無法實現。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM