是否可以使用 jQuery 检测 :after 或 :before 伪元素的点击?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15707588/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 15:38:37  来源:igfitidea点击:

Is it possible to detect a click of an :after or :before pseudo element with jQuery?

jquerycss

提问by dezman

Lets say I have:

可以说我有:

<div></div>

with:

和:

div {
    width: 500px;
    height: 500px;
    position: relative;
}
div:after {
    content: '';
    display: block;
    width: 20px;
    height: 20px;
    position: absolute;
    top: 0;
    right: 0;
}

Can I do something like $('div:after').click(function(){...});? And have it not fire if I am clicking on divbut not div:after.

我可以做类似的事情$('div:after').click(function(){...});吗?如果我点击div但不是,它就不会触发div:after

采纳答案by ryan

Maybe. Depending on how you structure your pseudo content you would have to rely on calculating mouse position for clicks on the actual div. The event handlers would all go on the div, and not the pseudo element because it doesn't exist in the DOM.

也许。根据您构建伪内容的方式,您将不得不依靠计算鼠标位置来点击实际 div。事件处理程序都在 div 上,而不是伪元素,因为它不存在于 DOM 中。

See Manipulating CSS :before and :after pseudo-elements using jQuery for some more info. Especially BoltClock's answer.

有关更多信息,请参阅使用 jQuery 操作 CSS :before 和 :after 伪元素 。尤其是 BoltClock 的回答。

Also see Felix's comment for another possible solution without mouse position: Only detect click event on pseudo-element

另请参阅 Felix 对另一种没有鼠标位置的可能解决方案的评论:仅检测伪元素上的点击事件