【问题标题】:field focus not working in firefox, setTimeout(function(){id.focus();},0);字段焦点在 Firefox 中不起作用,setTimeout(function(){id.focus();},0);
【发布时间】:2014-05-24 21:57:40
【问题描述】:

当我的应用程序在 Firefox 上运行时,我在 Firefox 中关注领域时遇到了问题,我阅读了很多 Question 这里(堆栈溢出)在我看到下面的代码来解决这个问题的所有答案中:

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

但是当你运行下面我必须在我的应用程序中实现的代码时,注意:这不是纯代码,它是一个演示。 请阅读代码里面写的cmets。

<!DOCTYPE html>
<html>
<body>
<head>
<script >
function abc(id,spanId){
var testVar = document.getElementById(id);
var spanVar = document.getElementById(spanId);

if(id.value =='') {
spanId.innerHTML = 'value is required';
//setTimeout(function(){id.focus();},0); //first close this line of code and execute it.
id.focus(); // then close this line and open comment of above line run it
return false;
}

}
</script>
</head>

<form>
<lable>Enter 1st value</lable><input type="text" onblur="abc(this,test_s1)"/>
<span id="test_s1"></span>
<lable>Enter 2nd value</lable><input type="text" onblur="abc(this,test_s2)"/>
<span id="test_s2"></span>
</form>
</body>
</html>

当您使用id.focus(); 执行代码时,它运行良好(在 Firefox 中有时,但在所有其他浏览器中运行良好,例如:chrome),但是当您使用 setTimeout(function(){id.focus();},0); 运行代码时,您将看到无限循环的焦点从两个文本字段开始。我该如何解决这种情况? 请在 Firefox 和 CHROME 浏览器中检查上述代码。 如果您不理解我的问题,请告诉我..

【问题讨论】:

    标签: javascript html google-chrome firefox focus


    【解决方案1】:

    使用 setTimeout 会导致循环,即下一个浏览器会在 setTimeout 函数运行第一个输入之前关注第二个输入。这会导致另一个 unfocus 事件,因为第一个输入由 setTimeout 聚焦,这会触发另一个 unfocus,这会触发另一个 unfocus .....

    您可以通过单击页面正文而不是下一个输入来看到 setTimeout 实际上完成了它的工作。

    您可以通过在全局变量中存储一个标志来说明最近是否发生了未聚焦事件,并在将焦点应用于 setTimeout 内的输入之前检查它来解决此问题。

    <script>
    var unfocusJustHappened = false;
    
    function abc(id,spanId){
        var testVar = document.getElementById(id);
        var spanVar = document.getElementById(spanId);
    
        if(id.value =='') {
            spanId.innerHTML = 'value is required';
    
            // Update flag
            unfocusJustHappened = true;
    
            setTimeout(function(){
    
                // If the flag is true
                if (unfocusJustHappened) {
                    id.focus();
                }
            },0);
    
            setTimeout(function(){
    
                // After a short period reset the flag to false
                unfocusJustHappened = false;
            },30)
    
            return false;
        }
    
    }
    </script>
    

    【讨论】:

      猜你喜欢
      • 2019-04-18
      • 2016-01-09
      • 1970-01-01
      • 2014-02-26
      • 1970-01-01
      • 1970-01-01
      • 2015-05-31
      • 2016-08-01
      • 2017-10-04
      相关资源
      最近更新 更多