最近更新: 2007-05-07

HTML Label 元件在 M$IE 上運作的狀況

jaceju 在《終於用 jQuery 做了一個有趣的服務》中提到: 光是要把 input:radio 隱藏卻要能動作的部份,足足花了我半個多小時 。他說若 Input 元件之 display 樣式設為 none ,或是 visibility 樣式設為 hidden ,表單送出時就會完全忽略它。所以他就把 Radio button 放到 Label 後面用背景遮住。

其實他是碰到了一個 IE 的 bug 。IE 對 Label for 的支援其實有 bug 存在,必須用 Label onclick 修正。

根據 W3C 規範,一個設定 display 樣式為 none 的表單元件依然會被送出。

A successful control is "valid" for submission.
... and controls that are not rendered because of style sheet settings may still be successful.
W3C Recommendation: Successful controls
<style type="text/css">
/*input[type="radio"]*//*IE6不支援 attribute selector*/
input {
    display: none;
}
</style>

<form method="POST">
  <label for="type1">Type1</label>
  <label for="type2">Type2</label>
  <input type="radio" id="type1" name="type[]" value="1" />
  <input type="radio" id="type2" name="type[]" value="2" />
  <button type="submit">送出</button>
</form>
<pre>
<?php
if (isset($_POST))
    var_dump($_POST);
?>
</pre>

我上述示範的 Label 用例,也是 W3C HTML 規範示範的用法。瀏覽器可以動作才是正常的,不能動作則我視為bug。

關於 Label 與 for 屬性的效果, IE 的實作並不完整(有bug)。我不能掌握它的動作。例如,如果我把 Radio button 放在 Label 之中,但 Label 沒加 for 屬性。IE竟然沒作用。

再者,當我設定 Label for 關聯的 Radio button 為可見時,點擊 Label 時將勾選 Radio button。但當設定內容為不可見(display=none or visibility=hidden)時, IE 竟無視 Label for 的作用而不勾選關聯的 Radio button (IE要用 onclick 修正)。在 FireFox 與 Opera 則完全可以運作。

各位還可參考 jaceju 關於 HTML label 元素無法作用 的心得,了解更多關於 IE 運行 Label 元件的實際效果。

<form method="POST">
  <label for="type1"
         onclick="document.getElementById('type1').checked=true;">
    Type1</label>
  <label for="type2"
         onclick="document.getElementById('type2').checked=true;">
    Type2</label>
  <input type="radio" id="type1" name="type[]" value="1" />
  <input type="radio" id="type2" name="type[]" value="2" />
  <button type="submit">送出</button>
</form>

上例示範為 Label 添加 onclick 處理動作,以修正 IE 對 Label for 效果實作不足的缺點。

樂多舊網址: http://blog.roodo.com/rocksaying/archives/3154125.html