Javascript 如何禁用 HTML 链接

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10276133/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 00:38:28  来源:igfitidea点击:

How to disable HTML links

javascriptjqueryhtmlcss

提问by Ankit

I have a link button inside a <td>which I have to disable. This works on IE but not working in Firefox and Chrome. Structure is - Link inside a <td>. I cannot add any container in the <td>(like div/span)

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

I tried all the following but not working on Firefox (using 1.4.2 js):

我尝试了以下所有但没有在 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');

Note - I cannot de-register the click function for the anchor tag as it is registered dynamically. AND I HAVE TO SHOW THE LINK IN DISABLED MODE.

注意 - 我无法取消注册锚标记的点击功能,因为它是动态注册的。我必须在禁用模式下显示链接。

回答by Adriano Repetti

You can't disable a link (in a portable way). You can use one of these techniques (each one with its own benefits and disadvantages).

您不能禁用链接(以可移植的方式)。您可以使用其中一种技术(每种技术都有自己的优点和缺点)。

CSS way

CSS方式

This should be the right way(but see later) to do it when most of browsers will support it:

当大多数浏览器都支持它时,这应该是正确的方法(但见下文):

a.disabled {
    pointer-events: none;
}

It's what, for example, Bootstrap 3.x does. Currently (2016) it's well supported only by Chrome, FireFox and Opera (19+). Internet Explorer started to support this from version 11 but not for linkshowever it's available in an outer element like:

例如,这就是 Bootstrap 3.x 所做的。目前(2016 年)只有 Chrome、FireFox 和 Opera(19+)才能很好地支持它。Internet Explorer 从版本 11 开始支持此功能,但不支持链接,但它在外部元素中可用,例如:

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

With:

和:

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

Workaround

解决方法

We, probably, need to define a CSS class for pointer-events: nonebut what if we reusethe disabledattribute instead of a CSS class? Strictly speaking disabledis not supported for <a>but browsers won't complain for unknownattributes. Using the disabledattribute IE will ignore pointer-eventsbut it will honor IE specific disabledattribute; other CSS compliant browsers will ignore unknowndisabledattribute and honor pointer-events. Easier to write than to explain:

我们,也许需要定义的CSS类pointer-events: none,但如果我们重用disabled属性,而不是一个CSS类?严格来说disabled不支持<a>但浏览器不会抱怨未知属性。使用disabled属性 IE 将忽略,pointer-events但会尊重 IE 特定disabled属性;其他 CSS 兼容浏览器将忽略未知disabled属性和荣誉pointer-events。写比解释更容易:

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

Another option for IE 11 is to set displayof link elements to blockor inline-block:

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

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

Note that this may be a portablesolution if you need to support IE (and you can change your HTML) but...

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

All this said please note that pointer-eventsdisables only...pointer events. Links will still be navigable through keyboardthen you also need to apply one of the other techniques described here.

所有这些都说请注意,pointer-events仅禁用...指针事件。链接仍可通过键盘导航,然后您还需要应用此处描述的其他技术之一。

Focus

重点

In conjunction with above described CSS technique you may use tabindexin a non-standard way to prevent an element to be focused:

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

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

I never checked its compatibility with many browsers then you may want to test it by yourself before using this. It has the advantage to work without JavaScript. Unfortunately (but obviously) tabindexcannot be changed from CSS.

我从来没有检查过它与许多浏览器的兼容性,所以你可能想在使用它之前自己测试它。它具有无需 JavaScript 即可工作的优势。不幸的是(但很明显)tabindex不能从 CSS 改变。

Intercept clicks

拦截点击

Use a hrefto a JavaScript function, check for the condition (or the disabled attribute itself) and do nothing in case.

使用hrefJavaScript 函数,检查条件(或禁用属性本身),以防万一。

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

To disable links do this:

要禁用链接,请执行以下操作:

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

To re-enable them:

要重新启用它们:

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

If you want instead of .is("[disabled]")you may use .attr("disabled") != undefined(jQuery 1.6+ will always return undefinedwhen the attribute is not set) but is()is much more clear (thanks to Dave Stewart for this tip). Please note here I'm using the disabledattribute in a non-standard way, if you care about this then replace attribute with a class and replace .is("[disabled]")with .hasClass("disabled")(adding and removing with addClass()and removeClass()).

如果你想要而不是.is("[disabled]")你可以使用.attr("disabled") != undefined(jQuery 1.6+ 将undefined在未设置属性时始终返回)但is()更清晰(感谢 Dave Stewart 提供此提示)。请注意,这里我使用的disabled属性在非标准的方式,如果你在乎这个,然后用一个类替换属性和替换.is("[disabled]").hasClass("disabled")(添加与删除addClass()removeClass())。

Zoltán Tamási noted in a commentthat "in some cases the click event is already bound to some "real" function (for example using knockoutjs) In that case the event handler ordering can cause some troubles. Hence I implemented disabled links by binding a return false handler to the link's touchstart, mousedownand keydownevents. It has some drawbacks (it will prevent touch scrolling started on the link)"but handling keyboard events also has the benefit to prevent keyboard navigation.

Zoltán Tamási在评论指出“在某些情况下,click 事件已经绑定到某个“真实”函数(例如使用 Knockoutjs)在这种情况下,事件处理程序的排序可能会导致一些麻烦。因此,我通过绑定返回来实现禁用链接链接的touchstart,mousedownkeydown事件的错误处理程序。它有一些缺点(它会阻止在链接上开始触摸滚动)”但处理键盘事件也有利于防止键盘导航。

Note that if hrefisn't cleared it's possible for the user to manually visit that page.

请注意,如果href未清除,用户可能会手动访问该页面。

Clear the link

清除链接

Clear the hrefattribute. With this code you do not add an event handler but you change the link itself. Use this code to disable links:

清除href属性。使用此代码,您无需添加事件处理程序,而是更改链接本身。使用此代码禁用链接:

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

And this one to re-enable them:

这是一个重新启用它们的方法:

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

Personally I do not like this solution very much (if you do not have to do more with disabled links) but it maybe more compatible because of various way to follow a link.

就我个人而言,我不太喜欢这个解决方案(如果你不必对禁用的链接做更多的事情),但它可能更兼容,因为链接的方式多种多样。

Fake click handler

假点击处理程序

Add/remove an onclickfunction where you return false, link won't be followed. To disable links:

添加/删除onclick您的功能return false,链接将不会被跟踪。要禁用链接:

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

To re-enable them:

要重新启用它们:

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

I do not think there is a reason to prefer this solution instead of the first one.

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

Styling

造型

Styling is even more simple, whatever solution you're using to disable the link we did add a disabledattribute so you can use following CSS rule:

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

a[disabled] {
    color: gray;
}

If you're using a class instead of attribute:

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

a.disabled {
    color: gray;
}

If you're using an UI framework you may see that disabledlinks aren't styled properly. Bootstrap 3.x, for example, handles this scenario and button is correctly styled both with disabledattribute and with .disabledclass. If, instead, you're clearing the link (or using one of the others JavaScript techniques) you must also handle styling because an <a>without hrefis still painted as enabled.

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

Accessible Rich Internet Applications (ARIA)

可访问的富互联网应用程序 (ARIA)

Do not forget to also include an attribute aria-disabled="true"together with disabledattribute/class.

不要忘记还包括一个属性aria-disabled="true"disabled属性/类。

回答by Ankit

Got the fix in css.

在 css 中得到了修复。

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

Above css when applied to the anchor tag will disable the click event.

当应用于锚标记时,上面的 css 将禁用单击事件。

For details checkout this link

有关详细信息,请查看此链接

回答by kross

Thanks to everyone that posted solutions (especially @AdrianoRepetti), I combined multiple approaches to provide some more advanced disabledfunctionality (and it works cross browser). The code is below (both ES2015 and coffeescript based on your preference).

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

This provides for multiple levels of defense so that Anchors marked as disable actually behave as such. Using this approach, you get an anchor that you cannot:

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

  • click
  • tab to and hit return
  • tabbing to it will move focus to the next focusable element
  • it is aware if the anchor is subsequently enabled
  • 点击
  • 制表符并按回车
  • 切换到它会将焦点移动到下一个可聚焦元素
  • 它知道锚点是否随后被启用


How to

如何

  1. Include this css, as it is the first line of defense. This assumes the selector you use is a.disabled

    a.disabled {
      pointer-events: none;
      cursor: default;
    }
    
  2. Next, instantiate this class on ready (with optional selector):

      new AnchorDisabler()
    
  1. 包括这个 css,因为它是第一道防线。这假设您使用的选择器是a.disabled

    a.disabled {
      pointer-events: none;
      cursor: default;
    }
    
  2. 接下来,在准备好时实例化这个类(使用可选的选择器):

      new AnchorDisabler()
    


ES2015 Class

ES2015 类

npm install -S key.js

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:

书信类:

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

回答by Kees C. Bakker

Try the element:

尝试元素:

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

Disabling a link works for me in Chrome: http://jsfiddle.net/KeesCBakker/LGYpz/.

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

Firefox doesn't seem to play nice. This example works:

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();
    }
});

Note: added a 'live' statement for future disabled / enabled links.
Note2: changed 'live' into 'on'.

注意:为将来禁用/启用的链接添加了“实时”声明。
注2:将'live'改为'on'。

回答by Yevgeniy Afanasyev

Bootstrap 4.1 provides a class named disabledand aria-disabled="true"attribute.

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

example"

例子”

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

More is on getbootstrap.com

更多信息请访问 getbootstrap.com

So if you want to make it dynamically, and you don't want to care if it is button or ancorthan in JS script you need something like that

所以如果你想动态地制作它,而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);
   }

But be carefull

但要小心

The solution only works on links with classes btn btn-link.

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

Sometimes bootstrap recommends using card-linkclass, in this case solution will not work.

有时引导程序建议使用card-link类,在这种情况下解决方案将不起作用

回答by isapir

I've ended up with the solution below, which can work with either an attribute, <a href="..." disabled="disabled">, or a class <a href="..." class="disabled">:

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

CSS Styles:

CSS 样式:

a[disabled=disabled], a.disabled {
    color: gray;
    cursor: default;
}

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

Javascript (in jQuery ready):

Javascript(在 jQuery 中):

$("a[disabled], a.disabled").on("click", function(e){

    var $this = $(this);
    if ($this.is("[disabled=disabled]") || $this.hasClass("disabled"))
        e.preventDefault();
})

回答by Joel Wiklund

In Razor (.cshtml) you can do:

在 Razor (.cshtml) 中,您可以执行以下操作:

@{
    var isDisabled = true;
}

<a href="@(isDisabled ? "#" : @Url.Action("Index", "Home"))" @(isDisabled ? "disabled=disabled" : "") class="btn btn-default btn-lg btn-block">Home</a>

回答by rgfpy

To disable link to access another page on touch device:

要禁用链接以访问触摸设备上的另一个页面:

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

回答by Pranav

you cannot disable a link, if you want that click event should not fire then simply Removethe actionfrom that link.

你不能禁用链接,如果你想要一个单击事件不应该那么火简单Removeaction从该链接。

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

For More Info :- Elements that can be Disabled

有关更多信息:- 可以禁用的元素

回答by mkk

I would do something like

我会做类似的事情

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

$('.disabled-link').on('click', false);

something like this should work. You add a class for links you want to have disabled and then you return false when someone click them. To enable them just remove the class.

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