一个选项是添加一个点击处理程序。就像这篇文章所说的,你可以通过调用
假设我有一个容器,当我点击它时,它会指向另一个页面。但是,我希望这个容器中的一些元素被禁用,所以当我点击它们时,链接将不起作用。我该怎么做?
例如,在这里我想禁用容器的红色部分。
a {
text-decoration: none;
color: white;
}
.container {
display: flex;
width: 400px;
height: 100px;
background-color: #ddd;
box-sizing: border-box;
padding: 5px;
}
.block-1 {
width: 50%;
height: 100%;
background-color: #3e3e3e;
text-align: center;
box-sizing: border-box;
padding-top: 20px;
}
.block-2 {
width: 50%;
height: 100%;
background-color: red;
text-align: center;
box-sizing: border-box;
padding-top: 20px;
}
<a href="#">
<div class="container">
<div class="block-1">Active</div>
<div class="block-2">Disabled</div>
</div>
</a>
您放入<a>
标记中的所有内容都是可点击的,因为"点击"事件实际上是在父标记(<a>
标记(上触发的,而不是在其内部触发的。
您需要将其分离——只需将一个div设为链接,另一个不设为链接。
a {
text-decoration: none;
color: white;
}
.container {
display: flex;
width: 400px;
height: 100px;
background-color: #ddd;
box-sizing: border-box;
padding: 5px;
}
.block-1 {
width: 50%;
height: 100%;
background-color: #3e3e3e;
text-align: center;
box-sizing: border-box;
padding-top: 20px;
}
.block-2 {
width: 50%;
height: 100%;
background-color: red;
text-align: center;
box-sizing: border-box;
padding-top: 20px;
}
<div class="container">
<a href="#" class="block-1">Active</a>
<div class="block-2">Disabled</div>
</div>
<!DOCTYPE html>
<html>
<head>
<title>Disable Link using CSS</title>
<style type="text/css">
.not-active {
pointer-events: none;
cursor: default;
}
</style>
</head>
<body>
<center>
<h1 style="color: green;">GeeksforGeeks</h1>
<h3>A Computer Science Portal for Geeks</h3>
<b>Disabled link:</b> To visit us
<a href="www.geeksforgeeks.org"
class="not-active">Click Here</a>
<br>
<br>
<b>Enabled link:</b> To use our ide
<a href=
"https://ide.geeksforgeeks.org/tryit.php">
Click Here</a>
</center>
</body>
</html>
e.preventDefault()
来告诉浏览器关注或不关注链接。
在下面的代码中,更改disabled
,即可打开/关闭链接。
不过,我应该补充一点,虽然我不是易访问性专家,但这不是很"语义",我猜这可能不适合屏幕阅读器。。。也许像aria-disabled
这样的东西可以用来解决这个问题,但我对它还不够熟悉。
var link = document.querySelector('a');
var disabled = true;
link.addEventListener('click', (e) => {
if (disabled) {
console.log('disabled');
e.preventDefault();
}
});
<a href="https://google.com">My link</a>