我們常會使用 element.focus() 方法,讓鍵盤游標停留在某個欄位上。例如說「會員登入」頁面開啟時,鍵盤輸入的游標就直接停在「帳號」欄位上,讓頁面開啟來後就可以直接輸入帳號。
但是當我畫面上的表單元素很多時,我會動態的將某些欄位隱藏,導致程式在執行 focus() 方法時會出現「控制項不可見、未啟動或無法接受焦點,因此無法將焦點移到控制項上。」的 JavaScript錯誤。
例如說下面的 HTML:
< html xmlns ="http://www.w3.org/1999/xhtml" lang ="tw" >
< head >
< title > 測試在 display:none 下的元素 </ title >
< script type ="text/javascript" >
window.onload = function ()
{
txtUsername = document.getElementById( 'username' );
txtUsername.focus()
}
</ script >
</ head >
< body >
< form >
< div style ="display:none;" >
< input type ="text" id ="username" name ="username" value ="" />
</ div >
</ form >
</ body >
</ html >
在執行的時候,就會出現以下錯誤訊息:
之前這個問題困擾我很久,雖然我最後是用 try / catch 的方式解決的,但最近找到 2 個不錯的方法:
1. 當該元素目前是被隱藏的狀態時,該元素的 offsetWidth 屬性的值一定是 0,所以你就可以修改 JavaScript 避開錯誤了,如下:
< html xmlns ="http://www.w3.org/1999/xhtml" lang ="tw" >
< head >
< title > 測試在 display:none 下的元素 </ title >
< script type ="text/javascript" >
window.onload = function ()
{
txtUsername = document.getElementById( 'username' );
if (txtUsername.offsetWidth != 0)
{
txtUsername.focus();
}
}
</ script >
</ head >
< body >
< form >
< div style ="display:none;" >
< input type ="text" id ="username" name ="username" value ="" />
</ div >
</ form >
</ body >
</ html >
2. 另外也可以用「更嚴謹」的方法來檢查 HTML 中的元素是否被隱藏,如下:
< html xmlns ="http://www.w3.org/1999/xhtml" lang ="tw" >
< head >
< title > 測試在 display:none 下的元素 </ title >
< script type ="text/javascript" >
function ElementIsVisible(elm)
{
if ( typeof (elm.style) != "undefined" &&
(
( typeof (elm.style.display) != "undefined"
&& elm.style.display == "none" )
||
( typeof (elm.style.visibility) != "undefined"
&& elm.style.visibility == "hidden" )
)
)
{
return false ;
}
else if ( typeof (elm.parentNode) != "undefined"
&& elm.parentNode != null
&& elm.parentNode != elm)
{
return ElementIsVisible(elm.parentNode);
}
return true ;
}
window.onload = function ()
{
txtUsername = document.getElementById( 'username' );
if (ElementIsVisible(txtUsername))
{
txtUsername.focus();
}
}
</ script >
</ head >
< body >
< form >
< div style ="display:none;" >
< input type ="text" id ="username" name ="username" value ="" />
</ div >
</ form >
</ body >
</ html >
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
