This article brings you three ways to bind events to HTML tag pseudo-elements. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
In a recent project, I encountered the function of clicking an icon to perform certain operations. It was originally very simple to implement, but the icon is implemented by ::after pseudo-element. In my impression, it seems that the pseudo-element cannot be directly performed. DOM operation, but all pages in the project display icons through pseudo elements, and it is not feasible to change the icons in all pages into DOM elements.
After checking on the Internet, most of them introduce the method of obtaining the mouse pointer coordinates through the event object to determine whether the clicked area is the area where the pseudo element is located, but this is very troublesome.
The following is a summary of several simple ways to implement event processing when clicking pseudo elements, with sample code attached.
HTML structure
First of all, the HTML structure is like this
<section> <span>按钮文字</span> </section>
Implementation method
The first one
Through CSS3 pointer-events characteristics 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>
The second type
realizes by preventing event bubbling
CSS basic code Same as above, change 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 method
Use the pointer coordinates of the event object to determine whether the click is within the range of the pseudo element. There are many ways to do this on the Internet. You can find it by going to Du Niang.
The last thing is, if it doesn’t work, don’t use ::after, replace it with the actual dom node, ah O(∩_∩)O haha~
This article is all here It’s over, for more other exciting content, you can pay attention to the HTML video tutorial column on the PHP Chinese website!
The above is the detailed content of Three ways to bind events to HTML tag pseudo-elements. For more information, please follow other related articles on the PHP Chinese website!

The roles of HTML, CSS and JavaScript in web development are: 1. HTML defines the web page structure, 2. CSS controls the web page style, and 3. JavaScript adds dynamic behavior. Together, they build the framework, aesthetics and interactivity of modern websites.

The future of HTML is full of infinite possibilities. 1) New features and standards will include more semantic tags and the popularity of WebComponents. 2) The web design trend will continue to develop towards responsive and accessible design. 3) Performance optimization will improve the user experience through responsive image loading and lazy loading technologies.

The roles of HTML, CSS and JavaScript in web development are: HTML is responsible for content structure, CSS is responsible for style, and JavaScript is responsible for dynamic behavior. 1. HTML defines the web page structure and content through tags to ensure semantics. 2. CSS controls the web page style through selectors and attributes to make it beautiful and easy to read. 3. JavaScript controls web page behavior through scripts to achieve dynamic and interactive functions.

HTMLisnotaprogramminglanguage;itisamarkuplanguage.1)HTMLstructuresandformatswebcontentusingtags.2)ItworkswithCSSforstylingandJavaScriptforinteractivity,enhancingwebdevelopment.

HTML is the cornerstone of building web page structure. 1. HTML defines the content structure and semantics, and uses, etc. tags. 2. Provide semantic markers, such as, etc., to improve SEO effect. 3. To realize user interaction through tags, pay attention to form verification. 4. Use advanced elements such as, combined with JavaScript to achieve dynamic effects. 5. Common errors include unclosed labels and unquoted attribute values, and verification tools are required. 6. Optimization strategies include reducing HTTP requests, compressing HTML, using semantic tags, etc.

HTML is a language used to build web pages, defining web page structure and content through tags and attributes. 1) HTML organizes document structure through tags, such as,. 2) The browser parses HTML to build the DOM and renders the web page. 3) New features of HTML5, such as, enhance multimedia functions. 4) Common errors include unclosed labels and unquoted attribute values. 5) Optimization suggestions include using semantic tags and reducing file size.

WebdevelopmentreliesonHTML,CSS,andJavaScript:1)HTMLstructurescontent,2)CSSstylesit,and3)JavaScriptaddsinteractivity,formingthebasisofmodernwebexperiences.

The role of HTML is to define the structure and content of a web page through tags and attributes. 1. HTML organizes content through tags such as , making it easy to read and understand. 2. Use semantic tags such as, etc. to enhance accessibility and SEO. 3. Optimizing HTML code can improve web page loading speed and user experience.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Atom editor mac version download
The most popular open source editor

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver CS6
Visual web development tools