Mar*_*eva 7 html javascript css
Look at the code of below, as you can see there is a close icon floated to the right of a span element.
span {
width: 100%;
display: inline-block;
}
span:after {
content: "\2715";
float: right;
position: absolute;
}
span:hover:after {
cursor: pointer;
}Run Code Online (Sandbox Code Playgroud)
<span>Content</span>Run Code Online (Sandbox Code Playgroud)
I want the :after to behave like a button. As you could see, it makes the cursor a pointer on hover. How can I make it to behave like a button? For example, how can I add an onclick function to it?
一般来说,伪元素将继承分配给“拥有”它的非伪元素的事件和事件行为。
因此,例如,click在上面添加事件侦听器<span>将导致该span elemenet的任何伪元素都继承相同的click事件行为。
如果要实现伪元素和“所有者”元素之间的独立性,就click行为(即仅针对“伪”元素的单击行为)而言,可以使用pointer-events如下所示的CSS属性:
const span = document.querySelector("span");
span.addEventListener("click", () => alert("hey!"));Run Code Online (Sandbox Code Playgroud)
span {
display: inline-block;
position: relative;
background:red;
/* Blocks the click event from firing when span is clicked */
pointer-events:none;
}
span:after {
content: "'Pesudo button' - click me!";
position: absolute;
margin-left:1rem;
background:green;
width:15rem;
text-align:center;
color:white;
/* Allows the click event to fire when the pesudo element is clicked */
pointer-events:all;
}
span:hover:after {
cursor: pointer;
}Run Code Online (Sandbox Code Playgroud)
<span>I own the pesudo element</span>Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
72 次 |
| 最近记录: |