對于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