禁用一个链接

最好别这样做

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

Look disabled

1
2
3
4
.isDisabled {
cursor: not-allowed;
opacity: 0.5;
}

Act disabled

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

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

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

1
2
3
4
5
6
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"

1
2
3
4
5
<span class="isDisabled">
<a href="http://yrq110.me" aria-disabled="true">
Disabled Link
</a>
</span>

1
2
3
4
5
6
7
8
9
10
.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代码

1
2
3
4
5
6
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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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.

参考

文章目录
  1. 1. Look disabled
  2. 2. Act disabled
  3. 3. Described as disabled
  4. 4. Toggle Code
  5. 5. 最后
  6. 6. 参考
|