當前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
Disable anchor tag的javascript代码(兼容IE和Firefox)
生活随笔
收集整理的這篇文章主要介紹了
Disable anchor tag的javascript代码(兼容IE和Firefox)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
對于anchor tags(<a></a>),IE支持一個非標準的"disabled"屬性,但支持也不完善,比如,如果這個anchor tage沒有 "href" 值,IE會把這個anchor設置為灰色,當然不能點擊,也沒有下劃線。但如果這個anchor tag有href值,IE并不會真的disable這個anchor,而只是把字的顏色設為灰色,并且可以點擊,也有下劃線。Firefox則完全不支持這個非標準的屬性。
??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
為了給所有的瀏覽器都提供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
總結
以上是生活随笔為你收集整理的Disable anchor tag的javascript代码(兼容IE和Firefox)的全部內容,希望文章能夠幫你解決所遇到的問題。