我有一个覆盖整个窗口的模态,但只是因为需要在.open.modal
上设置的模态变暗背景。 HTML看起来像这样:
<div class="modals">
<div class="open modal">
<div class="modal_inner">
<div class="white">
<div class="x"><img src="/assets/meeting/close.png"></div>
<div class="all">
<!-- ALL CONTENT HERE -->
</div>
</div>
</div>
</div>
<div class="open modal">
<!-- OTHER MODAL CAN BE OPEN ON TOP -->
</div>
</div>
当用户点击.white
(.open.modal
或更高版本)以外时,我想关闭模式。
如果在父级(在本例中为body
或下方)和子级(在本例中为.white
)之间单击,将如何注册将触发的Javascript事件?
我在React中有这个。
答案 0 :(得分:1)
有两种标准方法可以解决它:
在click
上挂钩.open.modal
并在那里做真正的工作
在click
上隐藏.white
并防止冒泡,因此点击.white
无法到达.open.modal
,因此无法触发它的处理程序
例如:
handleOpenModalClick(event) {
// Do the work
}
handleWhiteClick(event) {
event.stopPropagation();
}
示例:
class Example extends React.Component {
handleOpenModalClick(event) {
// Do the work
console.log("Do it");
}
handleWhiteClick(event) {
event.stopPropagation();
}
render() {
return (
<div>
<div className="open modal" onClick={this.handleOpenModalClick}>
<div className="white" onClick={this.handleWhiteClick}>
xxx
</div>
</div>
</div>
);
}
}
ReactDOM.render(
<Example />,
document.getElementById("react")
);
&#13;
.open.modal {
background: #ccc;
padding: 20px;
}
.white {
background: white;
}
&#13;
<div id="react"</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
&#13;
在click
上点.open.modal
,收到后,检查event.target
和.open.modal
之间的元素,然后检查.white
是否存在。如果是这样,就不要做这项工作。
handleClick(event) {
let node = event.target;
while (node && node !== event.currentTarget) {
if (node.classList.contains("white")) {
return; // Skip it
}
}
// Do the work
}
示例:
class Example extends React.Component {
handleClick(event) {
let node = event.target;
while (node && node !== event.currentTarget) {
if (node.classList.contains("white")) {
return; // Skip it
}
}
// Do the work
console.log("Do it!");
}
render() {
return (
<div>
<div className="open modal" onClick={this.handleClick}>
<div className="white">
xxx
</div>
</div>
</div>
);
}
}
ReactDOM.render(
<Example />,
document.getElementById("react")
);
&#13;
.open.modal {
background: #ccc;
padding: 20px;
}
.white {
background: white;
}
&#13;
<div id="react"</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
&#13;