我有这样一个基本结构
.container {
height: 100vh;
width: 100%;
pointer-events: none;
}
.click-layer {
background-color: #ccc;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
pointer-events: auto;
}
.box {
position: absolute;
top: 40px;
left: 40px;
width: 200px;
height: 100px;
background-color: rgba(10, 10, 10, 0.2);
pointer-events: auto;
}
function App() {
return (
<div className="container">
<canvas
className="click-layer"
onClick={() => console.log("Click on Layer 1")}
>
</canvas>
<div className="box" onClick={() => console.log("Click on box")}>
Box
</div>
</div>
);
}
我想在用户将鼠标悬停在框 上时产生悬停效果。例如,背景颜色应更改为“红色”。
但是点击事件将被忽略,因为我希望 .click-layer 接收这些事件。
有什么办法可以实现吗?提前致谢!
预期行为
- 将鼠标悬停在框中 => 背景颜色变为红色
- 点击框=>控制台日志“点击图层1”
function App() {
return (
<div className="container">
<canvas
className="click-layer"
onClick={() => console.log("Click on Layer 1")}
>
Layer 1
</canvas>
<div className="box" onClick={() => console.log("Click on box")}>
Box
</div>
</div>
);
}
ReactDOM.render(<App />, document.getElementById("root"));
.container {
height: 100vh;
width: 100%;
pointer-events: none;
}
.click-layer {
background-color: #ccc;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
pointer-events: auto;
}
.box {
position: absolute;
top: 40px;
left: 40px;
width: 200px;
height: 100px;
background-color: rgba(10, 10, 10, 0.2);
pointer-events: auto;
}
.box:hover {
background-color: red;
/* pointer-events: none; */
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>
最佳答案
与其将 onClick 事件提供给 .click-layer
和 .box
,不如将其提供给整个 .container
类.如果您选择其中任何一个,它会控制它。我希望这是你所期望的🤞。
<div className="container" onClick={() => console.log("Click on Container")}>
<div className="click-layer">Layer 1 </div>
<div className="box">
Box
</div>
</div>
function App() {
return (
<div className="container" onClick={() => console.log("Click on Container")}>
<div className="click-layer">Layer 1 </div>
<div className="box">
Box
</div>
</div>
);
}
ReactDOM.render(<App />, document.getElementById("root"));
.container {
height: 100vh;
width: 100%;
pointer-events: none;
}
.click-layer {
background-color: #ccc;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
pointer-events: auto;
}
.box {
position: absolute;
top: 40px;
left: 40px;
width: 200px;
height: 100px;
background-color: rgba(10, 10, 10, 0.2);
pointer-events: auto;
}
.box:hover {
background-color: red;
/* pointer-events: none; */
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>
关于javascript - 显示悬停效果但忽略点击事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65805675/