web front-end entry to the combat: Several HTML tags pseudo-element binding way to events

Here are several simple ways to achieve sorted out clickfor event processing pseudo-element, accompanied by sample code.

HTML structure

First, this is the HTML structure


<section>
    <span>按钮文字</span>
</section>

Implementation

The first

By
CSS3the
pointer-eventscharacteristics to achieve.

CSS code

<style>
    *{margin: 0; padding:0;}
    section{
        border: 1px solid #abc;
        border-radius: 5px;
        background-color: #def;
        font-family: Microsoft YaHei;
        height: 40px;
        box-sizing: border-box;
        cursor: pointer;
        font-size: 16px;
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);

        pointer-events: none;    /* 关键点在这里,元素禁止响应鼠标事件 */
    }

    section::after{
        content: '';
        border-left: 1px solid #abc;
        display: inline-block;
        width: 24px;
        height: 100%;
        background-size: contain;
        background-position: center;
        background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAYAAABXAvmHAAABEklEQVRoQ+2X3Q3CMAyE3Y3YBDZAbOBRzAaMwkiMgCqlUoX4SX13qiKcl77Uzn13ddpONviaBtdvBbB3gpVAJQA6UI8QaCBcXgnAFoINKgHQQLhcmoC738zsHhHzVbJkAE38uam+qCAkAC/iF+clEHSAD+JlEFSAH+IlEDSATvF0CArARvFUCBggKZ4GAQG4+8HMTuABHxHxyPaAALKbMusKgOlmptd/J9CG+JhxblVz3XWIhz5GFxeTEJSPO9oMbISgiJ8NpAHMzTohaOLpAB0QVPESgC8QdPEygDcQEvFSgBXEmD/14Mutu5x6CnXvSryxAIhmplpVAinbiEWVANHMVKtKIGUbsagSIJqZajV8Ak/MSlox+m54VQAAAABJRU5ErkJggg==);

        pointer-events: auto;    /* 关键点在这里,伪元素覆盖父元素的 pointer-events: none ,响应鼠标事件 */
    }

    section span{
        display: inline-block;
        height: 100%;
        vertical-align: top;
        line-height: 40px;
        padding-left: 10px;
    }
</style>

JavaScript code

<script>
    document.querySelector('section').addEventListener('click', ()=>{
        console.log('只有点击伪元素才能触发click');
    });
</script>
web前端开发学习Q-q-u-n: 784783012 ,分享学习的方法和需要注意的小细节,不停更新最新的教程和学习方法
(从零基础开始到前端项目实战教程,学习工具,职业规划)

The second

Achieved by blocking the way event bubbling

CSS code base as above, will pointer-events: none;and pointer-events: auto;.

<script>
    document.querySelector('section').addEventListener('click', ()=>{
        // 因为其他子元素事件冒泡被阻止了,所以点击section的时候,只剩下伪元素覆盖区域进入到事件监听中
        console.log('只有伪元素才能触发click');
    });

    document.querySelector('span').addEventListener('click', ev=>{
        // 阻止文字元素的事件冒泡
        ev.stopPropagation();
    });
</script>

The third

By
eventpointer coordinates of the object to determine whether clicks within the scope of pseudo-elements, this way online a lot, we have to look at the degree of your mother.

At last

The final step is, it is impossible not to use ::after, replaced by actual domnode it

Guess you like

Origin blog.51cto.com/14592820/2459102