为了保持页面简洁,有时候伪元素会做成类似关闭按钮之类的,并且需要点击事件,绑定方法:

  • 宿主元素设置  pointer-events:none;

  • 伪元素设置为  pointer-events:auto;

即可实现,不过兼容性有待测试,要求不高的场景可以直接上。

完整示例:伪元素点击事件实现

这个示例展示了如何为伪元素添加点击事件,同时保持宿主元素不响应点击:

<!DOCTYPE html>
<html lang="zh-CN">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>伪元素点击事件示例</title>
        <style>
            .notification {
                position: relative;
                padding: 15px 40px 15px 15px; /* 右侧留出关闭按钮空间 */
                background-color: #f0f0f0;
                border: 1px solid #ddd;
                border-radius: 4px;
                width: 300px;
                margin: 20px auto;
                pointer-events: none; /* 宿主元素不响应点击 */
                cursor: default;
            }

            .notification::after {
                content: '×';
                position: absolute;
                right: 10px;
                top: 50%;
                transform: translateY(-50%);
                font-size: 20px;
                color: #999;
                cursor: pointer;
                pointer-events: auto; /* 伪元素可以响应点击 */
            }

            .notification::after:hover {
                color: #333;
            }
        </style>
    </head>
    <body>
        <div class="notification" id="notification">
            这是一条通知消息,点击右侧的关闭按钮可以关闭我。
        </div>

        <script>
            // 通过事件委托或直接绑定到父元素来处理伪元素的点击
            document.querySelector('#notification').addEventListener('click', function(e) {
                // 检查点击位置是否在伪元素区域
                // 这里简化处理,实际应用中可能需要更精确的判断
                const rect = this.getBoundingClientRect();
                const clickX = e.clientX - rect.left;

                // 如果点击发生在右侧区域(假设是伪元素)
                if (clickX > rect.width - 30) {
                    console.log('关闭按钮被点击');
                    this.style.display = 'none';
                }
            });
        </script>
    </body>
</html>

说明

  • 宿主元素 .notification 设置了 pointer-events none;,使其不响应任何点击事件。

  • 伪元素 ::after 设置了 pointer-events auto;,使其可以正常响应点击。

  • 由于伪元素本身不能直接绑定事件监听器,我们通过事件委托的方式将点击事件绑定在父元素上。

  • 然后通过判断点击位置来确定是否点击了伪元素区域。

彩蛋

完整示例链接,请移步Cnb: Cnb中的完整示例