[聚合文章] 禁用一个链接

JavaScript 2017-11-22 11 阅读

最好别这样做

See the Pen disabled-link by yrq110 ( @yrq110 ) on CodePen .

Look disabled

.isDisabled {
  cursor: not-allowed;
  opacity: 0.5;
}

Act disabled

对于使用鼠标点击的情况,使用 pointer-events: none;

.isDisabled > a {
  color: currentColor;
  display: inline-block;  /* For IE11/ MS Edge bug */
  pointer-events: none; 
  text-decoration: none;
}

对于使用键盘enter的情况,使用JS绑定事件

var link = document.querySelector('a');
link.addEventListener('click', function (event){
  if (this.parentElement.classList.contains('isDisabled')) {
    event.preventDefault();
  }
});

Described as disabled

对于屏幕阅读软件(Screen Reader),添加aria属性: aria-disabled="true"

<spanclass="isDisabled">
  <ahref="http://yrq110.me"aria-disabled="true">
    Disabled Link
  </a>
</span>
.isDisabled {
  cursor: not-allowed;
  opacity: 0.5;
}
a[aria-disabled="true"] {
  color: currentColor;
  display: inline-block;  /* For IE11/ MS Edge bug */
  pointer-events: none;
  text-decoration: none;
}

考虑到防止误触,修改JS代码

document.body.addEventListener('click', function (event){
  // filter out clicks on any other elements
  if (event.target.nodeName == 'A' && event.target.getAttribute('aria-disabled') == 'true') {
    event.preventDefault();
  }
});

Toggle Code

function disableLink(link){
// 1. Add isDisabled class to parent span
  link.parentElement.classList.add('isDisabled');
// 2. Store href so we can add it later
  link.setAttribute('data-href', link.href);
// 3. Remove href
  link.href = '';
// 4. Set aria-disabled to 'true'
  link.setAttribute('aria-disabled', 'true');
}
function enableLink(link){
// 1. Remove 'isDisabled' class from parent span
  link.parentElement.classList.remove('isDisabled');
// 2. Set href
  link.href = link.getAttribute('data-href');
// 3. Remove 'aria-disabled', better than setting to false
  link.removeAttribute('aria-disabled');
}

最后

问题来了,什么时候会有这样的需求呢?

原作者最后的话:

Seriously folks, just don’t do it.

注:本文内容来自互联网,旨在为开发者提供分享、交流的平台。如有涉及文章版权等事宜,请你联系站长进行处理。