Disable anchor tag的javascript代码(兼容IE和Firefox)

对于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
原文地址:https://www.cnblogs.com/DotNetNuke/p/986466.html