Only detect click event on pseudo-element

前端 未结 10 1870
长情又很酷
长情又很酷 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:53

    This is edited answer by Fasoeu with latest CSS3 and JS ES6

    Edited demo without using JQuery.

    Shortest example of code:

    Some text

    p {
        position: relative;
        pointer-events: none;
    }
    p::before {
        content: "";
        position: absolute;
        pointer-events: auto;
    }
    p span {
        display: contents;
        pointer-events: auto;
    }
    
    const all_p = Array.from(document.querySelectorAll('p'));
    
    for (let p of all_p) {
        p.addEventListener("click", listener, false);
    };
    

    Explanation:

    pointer-events control detection of events, removing receiving events from target, but keep receiving from pseudo-elements make possible to click on ::before and ::after and you will always know what you are clicking on pseudo-element, however if you still need to click, you put all content in nested element (span in example), but because we don't want to apply any additional styles, display: contents; become very handy solution and it supported by most browsers. pointer-events: none; as already mentioned in original post also widely supported.

    The JavaScript part also used widely supported Array.from and for...of, however they are not necessary to use in code.

提交回复
热议问题