How to disable a link using only CSS?

前端 未结 22 2925
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-22 02:58

Is there any way to disable a link using CSS?

I have a class called current-page and want links with this class to be disabled so that no action occurs

22条回答
  •  -上瘾入骨i
    2020-11-22 03:42

    Thanks to everyone that posted solutions, I combined multiple approaches to provide some more advanced disabled functionality. Here is a gist, and the code is below.

    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
    
    
    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 such as (with optional selector):
        $ ->
          new AnchorDisabler()
    

    Here is the 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
    

提交回复
热议问题