最近打算模仿在线ps实现一个手稿上色的单页面应用,需要实现鼠标移入button弹出菜单,移出button菜单消失,鼠标移入菜单,菜单保持弹出的状态。一开始是想把弹出的菜单用absolute定位,然后将left置为button的范围内,这样可以实现效果,但是不美观,弹出的菜单很有可能会覆盖部分button。查阅了网上的方法:当鼠标移出button时,使用setTimeout设置菜单延时消失,当鼠标移入菜单时取消定时器。由于有多个按钮需要使用到这个效果,于是使用react写了一个弹出菜单的组件,效果如下:
代码如下:
RightPopBtn.tsx
// 鼠标移入自动弹出菜单,移出菜单自动消失,移出但移入菜单,菜单保持弹出状态,移出菜单,菜单消失
import React, { Component } from "react";
import "./index.css";
type EventFunc = () => {};
type Props = {
menuList: string[];
eventList: EventFunc[];
btnContent: string;
};
type State = {
showMenu: boolean;
};
export default class RightPopBtn extends Component<Props, State> {
timeout: number | undefined;
constructor(props: Props) {
super(props);
this.state = {
showMenu: false,
};
}
btnMouseEnterEvent() {
this.setState({
showMenu: true,
});
}
btnMouseLeaveEvent() {
// 设置延迟
this.timeout = window.setTimeout(() => {
this.setState({
showMenu: false,
});
}, 150);
}
menuMouseEnterEvent() {
clearTimeout(this.timeout!);
this.timeout = undefined;
this.setState({
showMenu: true,
});
}
menuMouseLeaveEvent() {
this.setState({
showMenu: false,
});
}
render() {
return (
<div style={{ position: "relative", textAlign: "center" }}>
<button
className="base-btn"
onMouseEnter={this.btnMouseEnterEvent.bind(this)}
onMouseLeave={this.btnMouseLeaveEvent.bind(this)}
>
{this.props.btnContent}
</button>
{this.state.showMenu ? (
<div
style={{
position: "absolute",
top: 0,
left: "100%",
minWidth: 100,
color: "#000000",
backgroundColor: "#f4f4f4",
zIndex: 10,
textAlign: "center",
}}
onMouseEnter={this.menuMouseEnterEvent.bind(this)}
onMouseLeave={this.menuMouseLeaveEvent.bind(this)}
>
{this.props.menuList.map((item, index) => {
return (
<div key={item} onClick={this.props.eventList[index]}>
{item}
</div>
);
})}
</div>
) : (
<div></div>
)}
</div>
);
}
}
index.css
.base-btn {
color: #d5d5d5;
background-color: rgba(0,0,0,0);
padding-left: 6px;
padding-right: 6px;
margin: 4px;
border: none;
outline: none;
}
注意这里的setTimeout,在vscode中查看发现有两个setTimeout,一个时typescript的lib下的,一个时node下的,而且两个函数的返回类型不一致,这里使用window.setTimeout即可解决。另外,在stackoverflow上找到一个解决类型冲突的方法
let timer: ReturnType<typeof setTimeout> = setTimeout(() => { ... });
clearTimeout(timer);