效果
点击红色按钮(后面统称按钮A),橘色表格(后面统称表格A)隐藏或者显示
点击页面空白区域,表格A隐藏
有两种方式
第一种: window/documen.addEventListener
第二种:onClick + onBlur
我使用的react + typescript + react-router(hash)
第一种
原理:给document绑定点击事件,点击的时候加判断,
如果点击的区域不在按钮A和表格A种,就关闭表格A,
如果在,则隐藏或者显示表格A
public componentDidMount() {
document.addEventListener("click", this.hiddenBox);
}
public componentWillUnmount() {
document.removeEventListener("click", this.hiddenBox);
}
/** hidden other link box (on top right of topNavBar) */
private hiddenBox(e: MouseEvent) {
const target = e.target as Node;
const gearIcon = document.getElementById("tes-topNavBar-gear");
const {showBox} = this.state;
if (gearIcon?.contains(target)) {
this.setState({showBox: !showBox});
} else {
if (showBox) this.setState({showBox: false});
}
}
#### 注意
在iframe里面不起作用
如下图,点击iframe中的区域,表格A仍然存在,并没有隐藏
原因:我的事件监听是加在document上面的,iframe不属于当前document,因此监听不起作用
第二种
原理:使用onClick和onBlur控制状态,根据状态来渲染表格A,这里我的状态用showBox来表示
onClick事件切换showBox ,onBlur把showBox设为false
#### 注意
1. 为了div标签能使用onBlur我给div加了一个tabIndex属性, 为了避免样式的影响,记得给这个div也加上
2. 因为onBlur不支持冒泡,如果你的表格A里面包含了 a、Link这样的元素,跳转是不生效的,
比方说这里的about,它其实是个Link标签
然后你会发现点击Link,不跳转了
这是我的解决方案:用div来写Link
如果是个a标签, 就用div来写a
改之前
修改后