2024-06-13 02:51:42 +08:00
|
|
|
|
|
|
|
|
|
|
|
|
2024-07-04 23:16:16 +08:00
|
|
|
interface HandleDropdownParams {
|
|
|
|
toggle: HTMLElement;
|
|
|
|
menu: HTMLElement;
|
|
|
|
showOnHover?: boolean,
|
|
|
|
onOpen?: Function | undefined;
|
|
|
|
onClose?: Function | undefined;
|
|
|
|
}
|
|
|
|
|
|
|
|
export function handleDropdown(options: HandleDropdownParams) {
|
|
|
|
const {menu, toggle, onClose, onOpen, showOnHover} = options;
|
2024-06-13 02:51:42 +08:00
|
|
|
let clickListener: Function|null = null;
|
|
|
|
|
|
|
|
const hide = () => {
|
|
|
|
menu.hidden = true;
|
|
|
|
if (clickListener) {
|
|
|
|
window.removeEventListener('click', clickListener as EventListener);
|
|
|
|
}
|
|
|
|
if (onClose) {
|
|
|
|
onClose();
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
const show = () => {
|
|
|
|
menu.hidden = false
|
|
|
|
clickListener = (event: MouseEvent) => {
|
|
|
|
if (!toggle.contains(event.target as HTMLElement) && !menu.contains(event.target as HTMLElement)) {
|
|
|
|
hide();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
window.addEventListener('click', clickListener as EventListener);
|
|
|
|
if (onOpen) {
|
|
|
|
onOpen();
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2024-07-04 23:16:16 +08:00
|
|
|
const toggleShowing = (event: MouseEvent) => {
|
2024-06-13 02:51:42 +08:00
|
|
|
menu.hasAttribute('hidden') ? show() : hide();
|
2024-07-04 23:16:16 +08:00
|
|
|
};
|
|
|
|
toggle.addEventListener('click', toggleShowing);
|
|
|
|
if (showOnHover) {
|
|
|
|
toggle.addEventListener('mouseenter', toggleShowing);
|
|
|
|
}
|
|
|
|
|
2024-08-04 01:01:54 +08:00
|
|
|
menu.parentElement?.addEventListener('mouseleave', hide);
|
2024-06-13 02:51:42 +08:00
|
|
|
}
|