首页 文章

如何禁用HTML链接

提问于
浏览
225

我在 <td> 里面有一个链接按钮,我必须禁用它 . 这适用于IE但不适用于Firefox和Chrome . 结构是 - 链接在 <td> 内 . 我无法在 <td> 中添加任何容器(如div / span)

我尝试了以下所有但不使用Firefox(使用1.4.2 js):

$(td).children().each(function () {
        $(this).attr('disabled', 'disabled');
  });


  $(td).children().attr('disabled', 'disabled');

  $(td).children().attr('disabled', true);

  $(td).children().attr('disabled', 'true');

注 - 我无法取消注册锚标记的click函数,因为它是动态注册的 . 我必须在禁用模式下显示链接 .

12 回答

  • 453

    您无法禁用链接(以便携方式) . 您可以使用这些技术之一(每种技术都有自己的优点和缺点) .

    CSS方式

    当大多数浏览器支持它时,这应该是 the right way (但稍后会看到):

    a.disabled {
        pointer-events: none;
    }
    

    只有Chrome,FireFox和Opera(19)才支持它.1105015_ . Internet Explorer从版本11开始支持此功能,但是not for links但它可以在外部元素中使用,例如:

    span.disable-links {
        pointer-events: none;
    }
    

    附:

    <span class="disable-links"><a href="#">...</a></span>
    

    解决方法

    我们可能需要为 pointer-events: none 定义一个CSS类,但是如果我们重用 disabled 属性而不是CSS类呢?严格来说 <a> 不支持 disabled ,但浏览器不会抱怨未知属性 . 使用 disabled 属性IE将忽略 pointer-events 但它将遵循IE特定的 disabled 属性;其他符合CSS标准的浏览器将忽略未知 disabled 属性并尊重 pointer-events . 写作比解释更容易:

    a[disabled] {
        pointer-events: none;
    }
    

    IE 11的另一个选项是将 display 的链接元素设置为 blockinline-block

    <a style="pointer-events: none; display: inline-block;" href="#">...</a>
    

    请注意,如果您需要支持IE(并且您可以更改HTML),这可能是一个可移植的解决方案,但......

    所有这些都说请注意 pointer-events 仅禁用...指针事件 . Links will still be navigable through keyboard 然后您还需要应用此处描述的其他技术之一 .

    焦点

    结合上述CSS技术,您可以以非标准方式使用 tabindex 来防止元素被聚焦:

    <a href="#" disabled tabindex="-1">...</a>
    

    我从未检查过它与许多浏览器的兼容性,那么你可能想在使用它之前自己测试它 . 它的优点是无需JavaScript即可工作 . 不幸的是(但显然) tabindex 无法从CSS更改 .

    拦截点击次数

    href 用于JavaScript函数,检查条件(或禁用的属性本身)并且不执行任何操作 .

    $("td > a").on("click", function(event){
        if ($(this).is("[disabled]")) {
            event.preventDefault();
        }
    });
    

    要禁用链接,请执

    $("td > a").attr("disabled", "disabled");
    

    要重新启用它们:

    $("td > a").removeAttr("disabled");
    

    如果你想要而不是 .is("[disabled]") ,你可以使用 .attr("disabled") != undefined (当没有设置属性时,jQuery 1.6将始终返回 undefined )但 is() 更清晰(感谢Dave Stewart的提示) . 请注意,我在非标准方式使用 disabled 属性,如果您关心这个,那么用类替换属性并将 .is("[disabled]") 替换为 .hasClass("disabled") (使用 addClass()removeClass() 添加和删除) .

    ZoltánTamásinoted in a comment那个"in some cases the click event is already bound to some "真正的“函数”(例如使用knockoutjs)在这种情况下,事件处理程序的排序会引起一些麻烦 . 因此,我通过将一个返回false处理程序绑定到链接的 touchstartmousedownkeydown 事件来实现禁用链接 . 它有一些缺点(它会阻止在链接上启动触摸滚动)“但处理键盘事件也有利于防止键盘导航 .

    请注意,如果 href 不是't cleared it',则用户可以手动访问该页面 .

    清除链接

    清除 href 属性 . 使用此代码,您不会添加事件处理程序,但您可以更改链接本身 . 使用此代码禁用链接:

    $("td > a").each(function() {
        this.data("href", this.attr("href"))
            .attr("href", "javascript:void(0)")
            .attr("disabled", "disabled");
    });
    

    而这一个重新启用它们:

    $("td > a").each(function() {
        this.attr("href", this.data("href")).removeAttr("disabled");
    });
    

    就个人而言,我不太喜欢这个解决方案(如果您不必使用已禁用的链接做更多),但由于链接的各种方式,它可能更兼容 .

    假单击处理程序

    添加/删除 onclick 函数,其中 return false ,链接将不会被跟踪 . 要禁用链接:

    $("td > a").attr("disabled", "disabled").on("click", function() {
        return false; 
    });
    

    要重新启用它们:

    $("td > a").removeAttr("disabled").off("click");
    

    我认为没有理由更喜欢这个解决方案而不是第一个解决方案 .

    造型

    样式更简单,无论您使用什么解决方案来禁用我们添加了 disabled 属性的链接,您都可以使用以下CSS规则:

    a[disabled] {
        color: gray;
    }
    

    如果您使用的是类而不是属性:

    a.disabled {
        color: gray;
    }
    

    如果您使用的是UI框架,则可能会看到已禁用的链接未正确设置样式 . 例如,Bootstrap 3.x处理这种情况并使用 disabled 属性和 .disabled 类正确设置了按钮的样式 . 相反,如果您正在清除链接(或使用其他JavaScript技术之一),则还必须处理样式,因为 <a> 没有 href 仍然被绘制为已启用 .

    可访问的富Internet应用程序(ARIA)

    不要忘记还包含属性 aria-disabled="true"disabled 属性/类 .

  • 0

    得到了CSS的修复 .

    td.disabledAnchor a{
           pointer-events: none !important;
           cursor: default;
           color:Gray;
    }
    

    应用于锚标记时,高于css将禁用click事件 .

    详情请查看link

  • 5

    感谢所有发布解决方案的人(尤其是@AdrianoRepetti),我结合了多种方法来提供更高级的 disabled 功能(并且它可以跨浏览器工作) . 代码如下(根据您的偏好,ES2015和coffeescript) .

    这提供了多级防御,因此标记为禁用的锚实际上表现如此 . 使用这种方法,你得到一个你不能的锚:

    • 点击

    • tab to并返回

    • tabbing to it会将焦点移动到下一个可聚焦元素

    • 它知道随后是否启用了锚


    如何

    • 包括这个css,因为它是第一道防线 . 假设您使用的选择器是 a.disabled
    a.disabled {
      pointer-events: none;
      cursor: default;
    }
    
    • 接下来,准备好实例化此类(使用可选的选择器):
    new AnchorDisabler()
    

    ES2015等级

    npm install -S key.js

    import {Key, Keycodes} from 'key.js'
    
    export default class AnchorDisabler {
      constructor (config = { selector: 'a.disabled' }) {
        this.config = config
        $(this.config.selector)
          .click((ev) => this.onClick(ev))
          .keyup((ev) => this.onKeyup(ev))
          .focus((ev) => this.onFocus(ev))
      }
    
      isStillDisabled (ev) {
        //  since disabled can be a class or an attribute, and it can be dynamically removed, always recheck on a watched event
        let target = $(ev.target)
        if (target.hasClass('disabled') || target.prop('disabled') == 'disabled') {
          return true
        }
        else {
          return false
        }
      }
    
      onFocus (ev) {
        //  if an attempt is made to focus on a disabled element, just move it along to the next focusable one.
        if (!this.isStillDisabled(ev)) {
          return
        }
    
        let focusables = $(':focusable')
        if (!focusables) {
          return
        }
    
        let current = focusables.index(ev.target)
        let next = null
        if (focusables.eq(current + 1).length) {
          next = focusables.eq(current + 1)
        } else {
          next = focusables.eq(0)
        }
    
        if (next) {
          next.focus()
        }
      }
    
      onClick (ev) {
        // disabled could be dynamically removed
        if (!this.isStillDisabled(ev)) {
          return
        }
    
        ev.preventDefault()
        return false
      }
    
      onKeyup (ev) {
        // We are only interested in disabling Enter so get out fast
        if (Key.isNot(ev, Keycodes.ENTER)) {
          return
        }
    
        // disabled could be dynamically removed
        if (!this.isStillDisabled(ev)) {
          return
        }
    
        ev.preventDefault()
        return false
      }
    }
    

    Coffescript类:

    class AnchorDisabler
      constructor: (selector = 'a.disabled') ->
        $(selector).click(@onClick).keyup(@onKeyup).focus(@onFocus)
    
      isStillDisabled: (ev) =>
        ### since disabled can be a class or an attribute, and it can be dynamically removed, always recheck on a watched event ###
        target = $(ev.target)
        return true if target.hasClass('disabled')
        return true if target.attr('disabled') is 'disabled'
        return false
    
      onFocus: (ev) =>
        ### if an attempt is made to focus on a disabled element, just move it along to the next focusable one. ###
        return unless @isStillDisabled(ev)
    
        focusables = $(':focusable')
        return unless focusables
    
        current = focusables.index(ev.target)
        next = (if focusables.eq(current + 1).length then focusables.eq(current + 1) else focusables.eq(0))
    
        next.focus() if next
    
    
      onClick: (ev) =>
        # disabled could be dynamically removed
        return unless @isStillDisabled(ev)
    
        ev.preventDefault()
        return false
    
      onKeyup: (ev) =>
    
        # 13 is the js key code for Enter, we are only interested in disabling that so get out fast
        code = ev.keyCode or ev.which
        return unless code is 13
    
        # disabled could be dynamically removed
        return unless @isStillDisabled(ev)
    
        ev.preventDefault()
        return false
    
  • -5

    尝试元素:

    $(td).find('a').attr('disabled', 'disabled');
    

    在Chrome中禁用链接适用于我:http://jsfiddle.net/KeesCBakker/LGYpz/ .

    Firefox看起来并不好玩 . 这个例子有效:

    <a id="a1" href="http://www.google.com">Google 1</a>
    <a id="a2" href="http://www.google.com">Google 2</a>
    
    $('#a1').attr('disabled', 'disabled');
    
    $(document).on('click', 'a', function(e) {
        if ($(this).attr('disabled') == 'disabled') {
            e.preventDefault();
        }
    });
    

    注意:为将来禁用/启用的链接添加了'live'语句 .
    注2:将'live'更改为'on' .

  • 11

    禁用链接以访问触摸设备上的其他页面 .

    if (control == false)
      document.getElementById('id_link').setAttribute('href', '');
    else
      document.getElementById('id_link').setAttribute('href', 'page/link.html');
    end if;
    
  • -1

    我最终得到了下面的解决方案,它可以使用属性 <a href="..." disabled="disabled"> 或类 <a href="..." class="disabled">

    CSS样式:

    a[disabled=disabled], a.disabled {
        color: gray;
        cursor: default;
    }
    
    a[disabled=disabled]:hover, a.disabled:hover {
        text-decoration: none;
    }
    

    Javascript(在jQuery中准备好):

    $("a[disabled], a.disabled").on("click", function(e){
    
        var $this = $(this);
        if ($this.is("[disabled=disabled]") || $this.hasClass("disabled"))
            e.preventDefault();
    })
    
  • 20

    您无法禁用链接,如果您希望点击事件不应该触发,那么只需从该链接 Remove action .

    $(td).find('a').attr('href', '');
    

    更多信息: - Elements that can be Disabled

  • -2

    我会做点什么的

    $('td').find('a').each(function(){
     $(this).addClass('disabled-link');
    });
    
    $('.disabled-link').on('click', false);
    

    这样的事情应该有效 . 您为要禁用的链接添加一个类,然后在有人单击它时返回false . 要启用它们,只需删除该类 .

  • 1

    Bootstrap 4.1提供了一个名为 disabledaria-disabled="true" 属性的类 .

    例”

    <a href="#" 
            class="btn btn-primary btn-lg disabled" 
            tabindex="-1" 
            role="button" aria-disabled="true"
    >
        Primary link
    </a>
    

    More is on getbootstrap.com

    因此,如果你想动态地创建它,并且 you don't want to care if it is button or ancor 比在JS脚本中你需要这样的东西

    let $btn=$('.myClass');
       $btn.attr('disabled', true);
       if ($btn[0].tagName == 'A'){
            $btn.off();
            $btn.addClass('disabled');
            $btn.attr('aria-disabled', true);
       }
    

    但要小心

    该解决方案仅适用于类 btn btn-link 的链接 .

    有时bootstrap建议使用 card-link 类,在本例中为解决方案 will not work .

  • 0

    还有另一种可能的方式,也是我最喜欢的方式 . 基本上它与lightbox禁用整个页面的方式相同,方法是放置一个div并摆弄z-index . 这是我的一个项目的相关片段 . This works in all browsers!!!!!

    Javascript(jQuery):

    var windowResizer = function(){
            var offset = $('#back').offset();   
            var buttontop = offset.top;
            var buttonleft = offset.left;
            $('#backdisabler').css({'top':buttontop,'left':buttonleft,'visibility':'visible'});
            offset = $('#next').offset();
            buttontop = offset.top;
            buttonleft = offset.left;
            $('#nextdisabler').css({'top':buttontop,'left':buttonleft,'visibility':'visible'});
    }
    
    $(document).ready(function() {
        $(window).resize(function() {   
            setTimeout(function() {
                windowResizer();
            }, 5); //when the maximize/restore buttons are pressed, we have to wait or it will fire to fast
        });
    });
    

    并在HTML中

    <a href="" id="back" style="float: left"><img src="images/icons/back.png" style="height: 50px; width: 50px" /></a>
    <a href="" id="next" style="float: right"><img src="images/icons/next.png" style="height: 50px; width: 50px" /></a>
    <img id="backdisabler" src="images/icons/disabled.png" style="visibility: hidden; position: absolute; padding: 5px; height: 62px; width: 62px; z-index: 9000"/>
    <img id="nextdisabler" src="images/icons/disabled.png" style="visibility: hidden; position: absolute; padding: 5px; height: 62px; width: 62px; z-index: 9000"/>
    

    因此,缩放器找到锚点(图像只是箭头)位置并将禁用器置于顶部 . 禁用程序的图像是半透明的灰色方块(更改html中禁用程序的宽度/高度以匹配您的链接)以显示它已被禁用 . 浮动允许页面动态调整大小,禁用程序将在windowResizer()中跟随 . 你可以通过谷歌找到合适的图像 . 为简单起见,我已将相关的CSS放在内联中 .

    然后基于某些条件,

    $('#backdisabler').css({'visibility':'hidden'});
    $('#nextdisabler').css({'visibility':'visible'});
    
  • 0

    您可以使用它来禁用asp.net的超链接或html中的链接按钮 .

    $("td > a").attr("disabled", "disabled").on("click", function() {
        return false; 
    });
    
  • 1

    我认为其中很多都是在思考 . 添加一个你想要的类,如 disabled_link .
    然后让css有 .disabled_link { display: none }
    现在用户可以't see the link so you won' t不得不担心他们点击它 . 如果他们做了一些事情来满足可点击的链接,只需用jQuery删除该类:
    $("a.disabled_link").removeClass("super_disabled") . 轰!

相关问题