我想制作一个水平呈 U 形的按钮,为此,我在现有按钮的顶部放置了一个白色伪元素,但问题是伪元素在它所在的部分仍然可以点击在按钮的顶部。
开始时,悬停时光标也发生了变化,但我通过将光标设置为自动来绕过它,因此伪元素上不会发生光标变化,但仍会触发点击事件。
这是CSS代码和代码笔链接: https://codepen.io/SawanSunar24/pen/KKxQvWm?editors=1111
.btn {
border: none;
height: 60px;
background-color: #3b82f6;
border-radius: 0 30px 30px 0;
color: white;
padding-top: 5px;
padding-bottom: 5px;
padding-left: 40px;
padding-right: 20px;
position: relative;
overflow: hidden;
cursor: pointer;
}
.btn::before {
background-color: white;
border-radius: 0 100% 100% 0;
bottom: 0px;
left: -20px;
content: "";
display: block;
height: 60px;
cursor: auto;
position: absolute;
width: 40px;
}
我将各种其他元素放在按钮顶部,但它们不可点击,并且此问题/条件仅发生在伪元素上。
如果有人能告诉我解决这个问题的方法,我将不胜感激,或者也许我只是愚蠢而且这是一种不好的做法,因此对更好的方法进行批评也会有所帮助。
谢谢。
你只需要添加
pointer-events: none;
到你的 before 元素。
const btn = document.querySelector(".btn");
btn.addEventListener("click", e => {
console.log("Data")
})
.main {
padding: 100px;
}
.btn {
border: none;
height: 60px;
background-color: #3b82f6;
border-radius: 0 30px 30px 0;
color: white;
padding-top: 5px;
padding-bottom: 5px;
padding-left: 40px;
padding-right: 20px;
position: relative;
overflow: hidden;
cursor: pointer;
}
.btn::before {
background-color: white;
border-radius: 0 100% 100% 0;
bottom: 0px;
left: -20px;
content: "";
display: block;
height: 60px;
cursor: auto;
position: absolute;
width: 40px;
/* ✨ Just add this one property ✨ */
pointer-events: none;
}
<div class="main">
<button class="btn">
Submit
</button
</div>
这个答案是针对相反的问题但是,可以应用相同的解决方案并让您的事件处理程序检查
event.target
;如果它是子元素什么也不做。
const btn = document.querySelector(".btn");
btn.addEventListener("click", (e) => {
if (e.target.tagName === "SPAN") {
e.preventDefault();
e.stopPropagation();
return false;
}
console.log("Data", e.target.tagName);
});
.main {
padding: 100px;
}
.btn {
border: none;
height: 60px;
background-color: #3b82f6;
border-radius: 0 30px 30px 0;
color: white;
padding-top: 5px;
padding-bottom: 5px;
padding-left: 40px;
padding-right: 20px;
position: relative;
overflow: hidden;
cursor: pointer;
}
.btn>span {
background-color: white;
border-radius: 0 100% 100% 0;
bottom: 0px;
left: -20px;
content: "";
display: block;
height: 60px;
cursor: auto;
position: absolute;
width: 40px;
}
<div class="main">
<button class="btn">
<span></span>
Submit
</button>
</div>