1. 程式人生 > >Firefox中元素獲取焦點函式focus不起作用的解決方法

Firefox中元素獲取焦點函式focus不起作用的解決方法

文章摘抄 http://openwares.net/firefox/firefox_element_focus_not_work.html

元素獲取焦點函式focus()在IE中正常Firefox中卻不起作用。

js校驗輸入框的函式

function is_number(feild) {
    var strRegExp = /^\d+(\.\d{1,2})?$/;
    if (!strRegExp.test(feild.value)) {
        alert("請輸入有效的數字,小數點後最多隻能輸入兩位!");
        feild.focus();
        return false;
    }
}

在IE中可以正常工作,在Firefox/(windows or linux)上卻無法重新獲取焦點。

有兩種解決辦法:

1、讓元素先失去焦點再獲取焦點
...
feild.blur();
feild.focus();
...

這種方法在Firefox/windows上行為是正常的,但在firefox/linux平臺上仍然無法獲取焦點

2、定時器
...
setTimeout(function(){feild.focus();},0);
...

這種方法在firefox/windows和firefox/linux平臺上都可以正常工作。

 例子

<script>
function init(){
    document.getElementById("inputId").focus();
} 
</script>

<body onload="document.getElementById('test').focus()">
我要獲取焦點:<input type="text" name="test" id="test">
</body>