无法在Safari中设置焦点 [英] Can't Set Focus in Safari

查看:132
本文介绍了无法在Safari中设置焦点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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)

更新-替换为工作代码

<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();

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

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

关于输入焦点的注释,无需用户干预

@zappullae发现

As found by @zappullae

在最近的iOS版本中,Apple似乎需要用户交互才能激活键盘,因此在页面加载时将无法实现.

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

这篇关于无法在Safari中设置焦点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆