/** * @description 获取当前文档标题。 */ export const getDocumentTitle = (): string => { return document.title } /** * @description 设置当前文档标题。 */ export const setDocumentTitle = (title: string): void => { document.title = title } /** * @description 重置输入元素的值,常用于清空文件输入框。 */ export const resetInput = (input: HTMLInputElement | null | undefined): void => { if (input === null || input === undefined) { return } input.value = "" } /** * @description Prevent double click selection, but allow drag selection. * * @see {@link https://www.cnblogs.com/walkermag/p/16700244.html} */ export const disableDoubleClickSelection = (event: MouseEvent): void => { if (event.detail > 1) { event.preventDefault() } } /** * @description Listen for clicks outside of the specified node, and execute * a callback when such clicks occur. */ export const onClickOutside = (node: HTMLElement | null, callback: () => void): (() => void) => { const handleClick = (event: MouseEvent): void => { if (event.target === null) { return } if (node !== null && node.contains(event.target as Node) === false) { callback() } } document.addEventListener("click", handleClick) return () => { document.removeEventListener("click", handleClick) } } /** * @description 表示注入脚本节点时可配置的选项。 */ export interface InjectScriptOptions { src: string onload?: NonNullable | undefined removeAfterLoaded?: boolean | undefined } /** * @description Inject a script into the document head. */ export const injectScript = (options: InjectScriptOptions): HTMLScriptElement => { const { src, onload, removeAfterLoaded } = options const script = document.createElement("script") script.setAttribute("type", "text/javascript") script.src = src script.addEventListener("load", (...args): void => { if (onload !== undefined) { onload.bind(script)(...args) } if (removeAfterLoaded === true) { script.remove() } }) document.head.append(script) return script } /** * @description 表示轮询查找 DOM 元素时可配置的选项。 */ export interface PollingToGetElementOptions { selector: string interval: number callback: (node: Element) => void } /** * @description Poll the DOM to get an element by selector, and execute a callback * when the element is found. */ export const pollingToGetElement = (options: PollingToGetElementOptions): void => { const { selector, interval, callback } = options let node: Element | null = null const fixedSelector = selector.includes("#") || selector.includes(".") ? selector : `#${selector}` node = document.querySelector(fixedSelector) const timer = setInterval(() => { node = node ?? document.querySelector(fixedSelector) if (node !== null) { clearInterval(timer) callback(node) } }, interval) }