在使用“指针事件: 无”时添加 CSS 游标属性

我试图禁用一个特定的链接和应用光标样式,但这个 CSS 命令 cursor: text;不会生效。光标始终是默认的。我使用的是最新的 Firefox 版本。

CSS:

pointer-events: none !important;
cursor: text;
color: Blue;
103962 次浏览

使用 pointer-events: none禁用所有鼠标交互与该元素。如果要更改 cursor属性,则必须将更改应用于父元素。您可以用元素包装链接并向其添加 cursor属性。

这里举个例子

超文本标示语言

<span class="wrapper">
<a href="#">Some Link</a>
</span>

CSS

.wrapper {
position: relative;
cursor: text;  /* This is used */
}
.wrapper a {
pointer-events: none;
}

不过,还是有一些浏览器不一致的地方。要在 IE11中实现这一点,似乎需要一个伪元素。伪元素还允许您选择 FF 中的文本。奇怪的是,你可以不用它在 Chrome 中选择文本。

更新例子

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

通过指定 pointer-events:none,可以主动声明元素和光标之间没有鼠标交互。因此,它也不能有一个光标-它是不可见的 所有鼠标的行为。

在这里可以找到证据。

删除 pointer-events: none !important;。使用 JavaScript 禁用链接:

anchorElement.onclick = function(){
return false;
}

如果您不知道 JavaScriptanchorElement是节点或元素本身。获取元素的最常见方法是使用 HTMLid属性。假设我们有:

<a id='whatever' href='#'>Text Here</a>

你的代码可以是:

document.getElementById('whatever').onclick = function(){
return false;
}

还有许多其他获取 Nodes 的方法。

距离最初的问题已经过去很长时间了,但这是我的解决方案,没有任何包装元素和光标,没有指针事件:

<!-- Add tabindex="-1" so that element cannot be reached by keyboard -->
<a href="url" aria-disabled="true" tabindex="-1" onfocus="blur()">Disabled link</a>

CSS:

/* Adding cursor just works: */
a[aria-disabled="true"] {
cursor: not-allowed;
}


/* Makes link non-clickable: */
a[aria-disabled="true"]:active {
pointer-events: none;
}

CodePen 示例

编辑:

  • Chrome 已经开始关注使用 tabindex 属性点击元素(即使使用 tabindex = “-1”)。最快的解决方案是将 onfocus="blur()"设置为 unfocus 元素。
  • 您需要防止聚焦元素,否则它可以被激活的输入键

编辑2

  • aria-disabled="true"代替 class="disabled"以满足 a11y;)

我的用例是一个可拖动的元素,它不能有任何指针事件,也不能有任何具有指针事件的父元素。

我解决了这个问题,有条件地应用一个全局样式,强制抓取光标只有在拖动。(我使用的是 React 和 styled-Component,但是同样的逻辑也可以应用于香草 js)。

const SetDraggingCursor = createGlobalStyle`
* {
cursor: grabbing !important;
}
`;


// ...


{isDragging && <SetDraggingCursor />}

您可以创建另一个 div,并将其放置在最后一个 div 上,然后生成如下 css:

.example{
background-color: rgba(255, 255, 255, 0); //opacity:0
z-index: 1;
cursor: not-allowed;
}

而不是包装,这可以做到这一点与纯 CSS 从内部以及。(我把它用在材料网页组件上,所以代码会更复杂一些。)

button:disabled {
> * {
cursor: not-allowed;
pointer-events: initial;
}


&::before {
background-color: #fff0;
}


&::after {
background-color: #fff0;
}
}
<button>
<svg .../>
</button>

我也尝试了 ::before::afterbutton:disabled直接,但就是不能让它发生..。