對於anchor tags(<a></a>),IE支援一個非標準的"disabled"屬性,但支援也不完善,比如,如果這個anchor tage沒有 "href" 值,IE會把這個anchor設定為灰色,當然不能點擊,也沒有底線。但如果這個anchor tag有href值,IE並不會真的disable這個anchor,而只是把字的顏色設為灰色,並且可以點擊,也有底線。Firefox則完全不支援這個非標準的屬性。
為了給所有的瀏覽器都提供disable anchor tage的功能,有這麼一些方法:
- 覆蓋(override)"onclick"事件,並讓這個事件什麼動作也不作,同時用CSS修改anchor的外觀。
更簡單的方法是:
- 如果想disable一個anchor,就去掉它的href屬性。所有的瀏覽器同時也會disable這個anchor,並且去掉所有的超連結外觀和反應,比如去掉底線,滑鼠不會變為手型,文字不會變為藍色,並且,這種方法disable的anchor文字不會變為無法修改的灰色。
為了實現這種效果,我們需要在刪除href屬性之前備份一個,備份可以儲存在一個我自己增加的非標準href_bak屬性中,下面是javascript實現代碼:
function disableAnchor(obj, disable){
if(disable){
var href = obj.getAttribute("href");
if(href && href != "" && href != null){
obj.setAttribute('href_bak', href);
}
obj.removeAttribute('href');
obj.style.color="gray";
}
else{
obj.setAttribute('href', obj.attributes['href_bak'].nodeValue);
obj.style.color="blue";
}
}
原文參見:IE and Firefox compatible javascript to enable or disable an anchor tag