我正在使用 CSS 在包含文本的元素上实现关闭按钮。关闭按钮是从具有 content:'X';
的伪元素生成的内容。我需要光标成为那个“X”上的指针,所以我使用了:
cursor:pointer;
它在 Chrome 和 Firefox 中运行良好,但在 Internet Explorer 中似乎不起作用(在 IE11 windows 7 上测试)。
DEMO (在IE中测试)
我也尝试过 cursor:hand;
但它没有解决问题。如何在悬停“X”但不悬停在 div 的文本上时使光标成为指针?
相关代码:
div{
font-size:2em;
position:relative;
display:inline-block;
}
div::before{
content:'X';
cursor:pointer;
display:block;
text-align:right;
}
<div>some text</div>
--编辑--
我知道在标记中创建一个子元素或 sibling 并将 cursor:pointer;
应用于它会起作用,但我想最小化标记并为关闭按钮使用一个伪元素,因为它没有语义值(value)。
最佳答案
我真的来晚了,但我现在才想出解决这个问题的办法。
此解决方案允许子元素上的指针,同时保留父元素上的默认光标。
(请参阅此处已接受的答案以获得不包括保持父元素的光标默认的解决方案:cursor: pointer doesn't work on :after element?)
首先,对于这个 hacky 解决方案,您必须放弃使用鼠标与父元素交互的能力。
将父元素设置为cursor: pointer
。
然后,将父元素设置为 pointer-events: none
将允许您“单击/悬停”父元素。
然后,对于伪元素,只需使用 pointer-events: auto
重新启用指针事件即可。
瞧!
div{
font-size:2em;
position:relative;
display:inline-block;
/* remove ability to interact with parent element */
pointer-events: none;
/* apply pointer cursor to parent element */
cursor:pointer;
/* make it more obvious which is child and which parent for example*/
background: darkred;
}
div::before{
content:'X';
display:block;
text-align:right;
/* restore ability to interact with child element */
pointer-events: auto;
/* make it more obvious which is child and which parent for example*/
width: 30px;
text-align: center;
background: white;
}
<div>some text</div>
关于css - 光标 :pointer on pseudo element IE,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26426734/