簡體   English   中英

未將焦點設置到 Firefox 中的文本字段

[英]Not setting focus to text field in Firefox

我遇到了一個非常有趣的問題。 我正在嘗試使用window.onLoad焦點設置在使用 Javascript(沒有 jQuery,我也嘗試過但沒有奏效)的輸入字段上。

看看這個小提琴: setFocusOnLoad

它在 chrome 瀏覽器中運行良好,但在 Firefox 中運行不正常。 Firefox 中是否有任何問題? 我該如何解決。

編輯:
這是我在html文件中復制的代碼:

<!DOCTYPE html>
<html>
    <head>
        <title></title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <script type="text/javascript">
            function onloadFocus(){
                var name = document.getElementById('name');
                //        name.value='window.onload called';
                name.focus();


            }

            window.onload=onloadFocus();
        </script>
    </head>
    <body>
        <div><input type='text' value='' id='name' name='name'></div>
    </body>
</html>

嘗試添加一點延遲:

function onloadFocus(){
    setTimeout(function() {
        document.getElementById('name').focus()
    }, 10);
}

更新 jsFiddle

必須將函數調用包裝成一個函數,否則會立即調用,而不是onLoad(此時輸入仍然未知):

window.onload=function(){onloadFocus();}

你應該使用window.onload=onloadFocus; 而不是window.onload=onloadFocus(); 因為在window.onload=onloadFocus(); onloadFocus 將立即運行,屆時輸入字段可能不可用。

提琴手

我得到了解決方案。 如果您想專注於 Firefox。 在腳本標簽的開始處編寫焦點函數。

<script type="text/javascript">
    document.getElementById('name').focus();
    // rest of the code here.
</script>

希望這會幫助你。

暫無
暫無

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

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