Programing

CSS 만 사용하여 링크를 비활성화하는 방법은 무엇입니까?

lottogame 2020. 9. 29. 07:08
반응형

CSS 만 사용하여 링크를 비활성화하는 방법은 무엇입니까?


CSS를 사용하여 링크를 비활성화하는 방법이 있습니까?

호출 된 클래스가 있으며이 클래스 current-page와의 링크를 비활성화하여 클릭 할 때 아무 작업도 발생하지 않도록합니다.


대답은 이미 질문의 의견에 있습니다. 가시성을 높이기 위해이 솔루션을 여기에 복사 합니다 .

.not-active {
  pointer-events: none;
  cursor: default;
  text-decoration: none;
  color: black;
}
<a href="link.html" class="not-active">Link</a>

브라우저 지원은 https://caniuse.com/#feat=pointer-events 를 참조 하십시오 . IE를 지원해야하는 경우 해결 방법이 있습니다. 이 답변을 참조하십시오 .

경고 : pointer-events비 SVG 요소에 대한 CSS 사용 은 실험적입니다. 이 기능은 CSS3 UI 초안 사양의 일부 였지만 많은 미해결 문제로 인해 CSS4로 연기되었습니다.


.disabled {
  pointer-events: none;
  cursor: default;
  opacity: 0.6;
}
<a href="#" class="disabled">link</a>


CSS는 스타일을 변경하는 데만 사용할 수 있습니다. 순수한 CSS로 할 수있는 최선의 방법은 링크를 완전히 숨기는 것입니다.

정말 필요한 것은 자바 스크립트입니다. 다음은 jQuery 라이브러리를 사용하여 원하는 작업을 수행하는 방법입니다.

$('a.current-page').click(function() { return false; });

CSS는 그렇게 할 수 없습니다. CSS는 프레젠테이션 전용입니다. 옵션은 다음과 같습니다.

  • 태그에 href속성을 포함하지 마십시오 <a>.
  • JavaScript를 사용하여 해당 앵커 요소를 찾고 그에 따라 또는 속성을 class제거하십시오 . jQuery는 당신을 도울 것입니다 (NickF는 비슷하지만 더 나은 것을하는 방법을 보여주었습니다).hrefonclick

부트 스트랩 비활성화 링크

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

<a href="#" class="btn btn-default btn-lg disabled" role="button">Link</a>

부트 스트랩 비활성화 버튼이지만 링크처럼 보입니다.

<button type="button" class="btn btn-link">Link</button>

href속성을 다음과 같이 설정할 수 있습니다.javascript:void(0)

.disabled {
  /* Disabled link style */
  color: black;
}
<a class="disabled" href="javascript:void(0)">LINK</a>


양식에서 HTML / CSS 만 사용하려는 경우 다른 옵션은 버튼을 사용하는 것입니다. 스타일을 지정하고 disabled속성을 설정하십시오 .

예 : http://jsfiddle.net/cFTxH/1/


CSS 전용이되도록하려면 비활성화 로직을 CSS로 정의해야합니다.

CSS 정의에서 논리를 이동하려면 속성 선택기를 사용해야합니다. 여기 몇 가지 예가 있어요 :

정확한 href가있는 링크 비활성화 : =

다음과 같이 특정 href 값을 포함하는 링크를 비활성화하도록 선택할 수 있습니다.

<a href="//website.com/exact/path">Exact path</a>

[href="//website.com/exact/path"]{
  pointer-events: none;
}

경로를 포함하는 링크를 비활성화합니다. *=

여기서 /keyword/경로에 포함 모든 링크 가 비활성화됩니다.

<a href="//website.com/keyword/in/path">Contains in path</a>

[href*="/keyword/"]{
  pointer-events: none;
}

다음으로 시작하는 링크 비활성화 : ^=

[attribute^=value]조작 대상 특정 값으로 시작하는 속성. 웹 사이트 및 루트 경로를 삭제할 수 있습니다.

<a href="//website.com/begins/with/path">Begins with path</a>

[href^="//website.com/begins/with"]{
  pointer-events: none;
}

비 https 링크를 비활성화하는 데 사용할 수도 있습니다. 예 :

a:not([href^="https://"]){
  pointer-events: none;
}

다음으로 끝나는 링크 비활성화 : $=

[attribute$=value]연산자 특성 타겟팅 특정 값으로 끝난다. 파일 확장자를 버리는 것이 유용 할 수 있습니다.

<a href="/path/to/file.pdf">Link to pdf</a>

[href$=".pdf"]{
  pointer-events: none;
}

또는 다른 속성

CSS는 모든 HTML 속성을 대상으로 할 수 있습니다. rel, target등이 될 수 있습니다 data-custom.

<a href="#" target="_blank">Blank link</a>

[target=_blank]{
  pointer-events: none;
}

속성 선택기 결합

여러 규칙을 연결할 수 있습니다. 모든 외부 링크를 비활성화하고 웹 사이트를 가리키는 링크는 비활성화하고 싶다고 가정 해 보겠습니다.

a[href*="//"]:not([href*="my-website.com"]) {
    pointer-events: none;
}

또는 특정 웹 사이트의 pdf 파일에 대한 링크를 비활성화합니다.

<a href="//website.com/path/to/file.jpg">Link to image</a>

[href^="//website.com"][href$=".jpg"] {
  color: red;
}

브라우저 지원

IE7부터 속성 선택기가 지원됩니다. :not()IE9부터 선택자.


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를 끄려면 다른 사람이 설명한대로 클릭 이벤트 또는 href를 교체해야합니다.

추신 : 명확히하기 위해 나는 이것이 상당히 어수선한 솔루션이라고 생각하고 SEO의 경우에도 최고는 아니지만 순전히 CSS로 최고라고 생각합니다.


이 시도:

<style>
.btn-disable {
    display:inline-block;
    pointer-events: none;       
}
</style>

포인터 이벤트 속성을 통해 제어 할 수 있습니다 방법 마우스로 HTML 요소의 응답 / 터치 이벤트 - CSS 호버 / 활성 상태, 클릭 / 자바 스크립트에서 탭 이벤트 및 커서가 표시되었는지를 포함.

그건 하지 당신이 유일한 방법 링크를 해제 하지만, 좋은 CSS의 방법 IE10 + 모든 새로운 브라우저에서 작동하는 :

.current-page {
  pointer-events: none;
  color: grey;
}
<a href="#" class="current-page">This link is disabled</a>


나는 인터넷을 통해 검색했고 이것 보다 더 나은 것을 발견하지 못했다 . 기본적으로 버튼 클릭 기능을 비활성화하려면 다음과 같이 jQuery를 사용하여 CSS 스타일을 추가하면됩니다.

$("#myLink").css({ 'pointer-events': 'none' });

그런 다음 다시 활성화하려면 다음을 수행하십시오.

$("#myLink").css({ 'pointer-events': '' });

Firefox 및 IE 11에서 확인하면 작동했습니다.


이 CSS를 사용할 수 있습니다.

a.button,button {
    display: inline-block;
    padding: 6px 15px;
    margin: 5px;
    line-height: 1.42857143;
    text-align: center;
    white-space: nowrap;
    vertical-align: middle;
    -ms-touch-action: manipulation;
    touch-action: manipulation;
    cursor: pointer;
    -webkit-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
    background-image: none;
    border: 1px solid rgba(0, 0, 0, 0);
    border-radius: 4px;
    -moz-box-shadow: inset 0 3px 20px 0 #cdcdcd;
    -webkit-box-shadow: inset 0 3px 20px 0 #cdcdcd;
    box-shadow: inset 0 3px 20px 0 #cdcdcd;
}

a[disabled].button,button[disabled] {
    cursor: not-allowed;
    opacity: 0.4;
    pointer-events: none;
    -webkit-touch-callout: none;
}

a.button:active:not([disabled]),button:active:not([disabled]) {
    background-color: transparent !important;
    color: #2a2a2a !important;
    outline: 0;
    -webkit-box-shadow: inset 0 3px 5px rgba(0, 0, 0, .5);
    box-shadow: inset 0 3px 5px rgba(0, 0, 0, .5);
}
<button disabled="disabled">disabled!</button>
<button>click me!</button>
<a href="http://royansoft.com" disabled="disabled" class="button">test</a>
<a href="http://royansoft.com" class="button">test2</a>


나는 사용했다 :

.current-page a:hover {
pointer-events: none !important;
}

그리고 충분하지 않았습니다. 일부 브라우저에서는 여전히 링크가 깜박이며 표시됩니다.

나는 추가해야했다 :

.current-page a {
cursor: text !important;
}

솔루션을 게시 한 모든 사람 덕분에 몇 가지 고급 disabled기능 을 제공하기 위해 여러 접근법을 결합했습니다 . 다음은 요점 이며 코드는 다음과 같습니다.

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

다음은 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

링크를 덮도록 다른 요소의 크기를 조정할 수도 있습니다 (오른쪽 Z- 색인 사용). 그러면 클릭이 "먹어"집니다.

(우리는 브라우저 창이 모바일 크기 일 때 H2가 그들을 덮는 "반응 형"디자인으로 인해 갑자기 비활성화 된 링크 문제가 있었기 때문에 우연히 이것을 발견했습니다.)


여기 데모
이 하나를 시도

$('html').on('click', 'a.Link', function(event){
    event.preventDefault();
});

<a href="#!">1) Link With Non-directed url</a><br><br>

<a href="#!" disabled >2) Link With with disable url</a><br><br>


Another trick is to place a invisible element above it. This will disable any hover effects as well

.myButton{
    position: absolute;
    display: none;
}

.myButton::after{ 
    position: absolute;
    content:"";
    height:100%;
    width:100%;
    top:0;
    left:0;
}

It's possible to do it in CSS

.disabled{
  cursor:default;
  pointer-events:none;
  text-decoration:none;
  color:black;
}
<a href="https://www.google.com" target="_blank" class="disabled">Google</a>

See at:

Please note that the text-decoration: none; and color: black; is not needed but it makes the link look more like plain text.


pointer-events:none will disable the link:

.disabled {
       pointer-events:none;
}
<a href="#" class="disabled">link</a>

참고URL : https://stackoverflow.com/questions/2091168/how-to-disable-a-link-using-only-css

반응형