我想识别 div 元素外的点击并基于它关闭下拉菜单。但是,单击 div 元素(包含输入元素和 svg)内的 svg 元素会将其识别为单击 div 元素外部。不知道如何解决它。我试过使用如下的css技巧,
button > * {
pointer-events: none;
}
但它也没有奏效。
我想做什么?
我有一个表单输入元素。在其中我有一个带有上下 svgs 下拉菜单的输入。因此,当我单击 svg 时,它会将其识别为文档单击。
class Parent extends React.PureComponent {
state = {
opened: false,
};
componentDidMount(){
document.addEventListener('click', this.handle_document_click);
}
arrow_up_click = (e) => {
e.stopPropagation();
e.PreventDefault();
}
arrow_down_click = (e) => {
e.stopPropagation();
e.PreventDefault();
}
handle_document_click = () => {
if (this.input_ref.current &&
this.input_ref.current.contains(e.target)) {
return;
}
this.setState({opened: false});
};
render = () => {
return (
<form onsubmit={handle_submit}>
<div ref={this.input_ref}>
<input/>
<button>
{state.opened && <SvgUp height="22" width="22"/
onClick={arrow_up_click}>}
{!state.opened && <SvgDown height="22"
width="22" onClick={arrow_down_click}/>}
</button>
</div>
</form>
)
}
}
有人可以帮我解决这个问题。我希望对 svg 的点击不被识别为文档点击。谢谢。
最佳答案
您可以根据组件的状态更改 SVG 图标。当您换出的 SVG 事件到达事件处理程序时,它不再“包含”在 div 中。
在这个非常相似的问题中找到了答案:
Why a click on svg element is not captured by node contains method?
这意味着您不必禁用所有 SVG:s 的指针事件,而只需用包含 pointer-events: none;
的 css 类的 div 包装被换出的组件。 .
关于javascript - 为什么使用 .contain 方法在节点内没有识别 svg?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57664614/