Disable anchor tag的javascript代碼(相容IE和Firefox)

來源:互聯網
上載者:User
對於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

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.