Only detect click event on pseudo-element

前端 未结 10 2082
长情又很酷
长情又很酷 2020-11-22 08:00

My code is:

p {
    position: relative;
    background-color: blue;
}

p:before {
    content: \'\';
    position: absolute;
    left:100%;
    width: 10px;
         


        
10条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-22 08:52

    On modern browsers you can try with the pointer-events css property (but it leads to the impossibility to detect mouse events on the parent node):

    p {
        position: relative;
        background-color: blue;
        color:#ffffff;
        padding:0px 10px;
        pointer-events:none;
    }
    p::before {
        content: attr(data-before);
        margin-left:-10px;
        margin-right:10px;
        position: relative;
        background-color: red;
        padding:0px 10px;
        pointer-events:auto;
    }
    

    When the event target is your "p" element, you know it is your "p:before".

    If you still need to detect mouse events on the main p, you may consider the possibility to modify your HTML structure. You can add a span tag and the following style:

    p span {
        background:#393;
        padding:0px 10px;
        pointer-events:auto;
    }
    

    The event targets are now both the "span" and the "p:before" elements.

    Example without jquery: http://jsfiddle.net/2nsptvcu/

    Example with jquery: http://jsfiddle.net/0vygmnnb/

    Here is the list of browsers supporting pointer-events: http://caniuse.com/#feat=pointer-events

提交回复
热议问题