`
javatoyou
  • 浏览: 1007953 次
  • 性别: Icon_minigender_2
  • 来自: 北京
文章分类
社区版块
存档分类
最新评论

如何檢查 HTML 中的元素是否被隱藏

 
阅读更多

我們常會使用 element.focus() 方法,讓鍵盤游標停留在某個欄位上。例如說「會員登入」頁面開啟時,鍵盤輸入的游標就直接停在「帳號」欄位上,讓頁面開啟來後就可以直接輸入帳號。

但是當我畫面上的表單元素很多時,我會動態的將某些欄位隱藏,導致程式在執行 focus() 方法時會出現「控制項不可見、未啟動或無法接受焦點,因此無法將焦點移到控制項上。」的 JavaScript錯誤。

例如說下面的 HTML:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<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 避開錯誤了,如下:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<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 中的元素是否被隱藏,如下:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<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>
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics