Event listener on a CSS pseudo-element, such as ::after and ::before?

我的未来我决定 提交于 2019-12-17 16:02:17

问题


I have a div element with a CSS pseudo-element ::before used as a close button (instead of using an actual button). How do I apply an event listener to only the pseudo-element?

HTML

<div id="box"></div>

CSS

#box:before
{
 background-image: url(close.png);
 content: '';
 display: block; 
 height: 20px;
 position: absolute;
 top: -10px;
 right: -10px; 
 width: 20px;
}

#box
{
 height: 100px;
 width: 100px;
}

回答1:


No. The pseudo-element does not exist in the DOM so it has no HTMLElementNode object representing it.




回答2:


Was looking for a solution and found this thread. Now want to share my solution:

CSS

element { pointer-events: none; }
element::after { pointer-events: all; }

JS

element.addEventListener('click', function() { ... });

This works if you don't need any pointer events on element. Check it in action.




回答3:


There is no :before and :after selector in jQuery. However as an alternative, you can check the location of the click event and check if it is on your pseudo-element:

(I haven't tested this)

style:

#mything {
    width: 100px;
    height: 100px;
    position: relative;
    background: blue;
}
#mything:after {
    content: "x";
    font-size: 10px;
    position: absolute;
    top: 0;
    right: 0;
    background: red;
    width: 10px;
    height: 10px;
}

javascript:

$('#mything').click(function(e) {
    if (e.clientX > $(this).offset().left + 90 &&
        e.clientY < $(this).offset().top + 10) {
        // do something
    }
});

html:

<div id="mything">Foo</div>



回答4:


If the position and dimensions of the generated content are known, you can add a click handler on the element itself and check the relative mouse position before handling it.

This is perverse, but possible.




回答5:


Generally speaking no as indicated by others. But in case your tag with pseudo-element is empty, such as glyphicon in bootstrap.

You can wrap a div or span or whatever tag suitable in your case. Glyphicons in bootstrap uses :before but on the page you can see that it has hover event caught.

Example:

<span>
  <span class="glyphicon glyphicon-asterisk" aria-hidden="true"></span>
</span>

Suppose you want to add event to the above glyphicon, you can use jquery parent selector

$('glyphicon').parent('span').click(function() { 
  // awesome things
});

Just a small trick in case your tag is empty.



来源:https://stackoverflow.com/questions/9395858/event-listener-on-a-css-pseudo-element-such-as-after-and-before

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!