是否有一种方法禁用链接使用CSS?
我有一个名为current-page的类,并希望禁用该类的链接,以便在单击它们时不发生任何操作。
是否有一种方法禁用链接使用CSS?
我有一个名为current-page的类,并希望禁用该类的链接,以便在单击它们时不发生任何操作。
当前回答
我结合了多种方法来提供一些更高级的禁用功能。这里有一个要点,代码如下。
这提供了多个级别的防御,因此标记为禁用的锚实际上是禁用的。
使用这种方法,你可以得到一个锚,你不能:
点击 按TAB键返回 标签将焦点移动到下一个可聚焦的元素 它知道锚是否随后被启用
Include this CSS content, as it is the first line of defense. This assumes the selector you use is 'a.disabled'. a.disabled { pointer-events: none; cursor: default; } Next, instantiate this class such as (with optional selector): $ -> new AnchorDisabler() Here is the CoffeeScript 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 JavaScript 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
其他回答
在CSS中可以做到这一点:
.disabled { 光标:违约; pointer-events:没有; 文字修饰:没有; 颜色:黑色; } <a href="https://www.google.com" target="_blank" class="disabled">谷歌</a>
看:
请注意文字装饰:无;颜色:黑色;不是必需的,但它使链接看起来更像纯文本。
CSS只能用来改变一些东西的样式。使用纯CSS所能做的最好的事情就是完全隐藏链接。
您真正需要的是一些JavaScript代码。下面是如何使用jQuery库完成您想做的事情。
$('a.current-page').click(function() { return false; });
你可以用CSS来做这件事的一种方法是在包装div上设置一个CSS,你设置它消失,其他东西会取代它的位置。
例如:
<div class="disabled">
<a class="toggleLink" href="wherever">blah</a>
<span class="toggleLink">blah</span
</div>
使用CSS
.disabled a.toggleLink { display: none; }
span.toggleLink { display: none; }
.disabled span.toggleLink { display: inline; }
要真正关闭a,您必须替换它的click事件或href,如其他人所述。
PS:澄清一下,我认为这是一个相当不整洁的解决方案,对于SEO来说也不是最好的,但我相信它是纯CSS最好的。
指针事件属性允许控制HTML元素如何 响应鼠标/触摸事件-包括CSS悬停/活动状态, 在JavaScript中点击/点击事件,以及光标是否在 可见。
这不是禁用链接的唯一方法,但这是一个很好的CSS方法,适用于Internet Explorer 10(及更高版本)和所有新浏览器:
.current-page { pointer-events:没有; 颜色:灰色; } <a href="#" class="current-page">该链接被禁用</a> .
Pointer-events:none将禁用该链接:
.disabled {
pointer-events: none;
}
<a href="#" class="disabled">link</a>