Only detect click event on pseudo-element

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

    Actually, it is possible. You can check if the clicked position was outside of the element, since this will only happen if ::before or ::after was clicked.

    This example only checks the element to the right but that should work in your case.

    span = document.querySelector('span');
    
    span.addEventListener('click', function (e) {
        if (e.offsetX > span.offsetWidth) {
            span.className = 'c2';
        } else {
            span.className = 'c1';
        }
    });
    div { margin: 20px; }
    span:after { content: 'AFTER'; position: absolute; }
    
    span.c1 { background: yellow; }
    span.c2:after { background: yellow; }
    ELEMENT

    JSFiddle

提交回复
热议问题