前端 伪类元素如何添加点击事件

首先展示基础代码

<style>
    // 伪类元素父盒子
    .button-text {
       width: 300px;
       height: 200px;
       background-color: antiquewhite;
     }

    // 给元素添加 伪类元素
    .button-text::after {
       content: '';
       width: 30px;
       height: 30px;
       background-color: red;
       display: block;
       transform: translateX(100px) translateY(100px);
    }
    </style>
</head>

<body>
    // 元素
    <div class="button-text"></div>
</body>

产生的效果如下:

        思考:如何让 红色方块点击后会有事件?

        利用事件冒泡原则

        当我给盒子添加 点击事件的时候 他会事件冒泡到父元素上,

        所以 给父元素点击事件,那么红色的方块也会触发事件

因此我们首先给父元素 添加点击事件

    const button = document.querySelector('.button-text')
    button.addEventListener('click', () => {
        console.log('被点击了');
    })

第二步 使用 pointer-events 这个属性 来控制这个元素是否可以触发事件

.button-text {
    // ....
    pointer-events: none;  // 禁止触发事件
}

.button-text::after {
    content: '';
    // ....

    pointer-events:all;  // 可以触发事件
}

        这样就可以达到 让伪元素添加事件的效果了。

        也可以避免组件冗余,添加类名即可

猜你喜欢

转载自blog.csdn.net/Kerwin__li/article/details/129122358
今日推荐