dom 封装的一些 dom 操作函数
ts
/**
* 移入元素后禁用右键菜单,移出之后恢复
* @param el
*/
export function disableRightClick(el: string | HTMLElement) {
const ele = typeof el === 'string' ? (document.querySelector(el) as HTMLElement) : el
const { oncontextmenu } = document
const { onmousedown } = document
ele.onmouseenter = () => {
const click = (e: any) => {
if (e.button === 2) {
const tag = e.srcElement || e.target
if (tag.type === 'text' || tag.type === 'textarea') {
document.oncontextmenu = () => false
} else {
document.oncontextmenu = () => false
}
}
}
document.onmousedown = click
document.oncontextmenu = () => false
}
ele.onmouseleave = () => {
document.oncontextmenu = oncontextmenu
document.onmousedown = onmousedown
}
}
export function uploadFn(option?: { accept?: string; multiple?: boolean }): Promise<File[]> {
return new Promise(resolve => {
const input = document.createElement('input')
input.accept = option?.accept || '*'
input.type = 'file'
input.multiple = !!option?.multiple
input.click()
input.onchange = () => {
resolve(input.files as any as File[])
}
})
}
export function isChild(parent: HTMLElement | null, child: HTMLElement | null) {
if (!parent || !child) return false
if (parent === child) return false
if (parent.contains(child)) return true
return isChild(parent.parentElement, child)
}
/**
* 禁止debugger
* 当窗口inner和outer尺寸不一致时会通过判断打开了控制台,然后将window.isDebug赋值为true
*/
export function disableDebug() {
function block() {
if (
window.outerHeight - window.innerHeight > 200 ||
window.outerWidth - window.innerWidth > 200
) {
document.body.innerHTML = '检测到非法调试,请关闭后刷新重试!'
// @ts-ignore
window.isDebug = true
}
setInterval(() => {
;(function () {
return false
})
['constructor']('debugger')
['call']()
}, 50)
}
try {
block()
} catch (err) {
console.log(err)
}
}
export function disableContextMenu() {
document.oncontextmenu = () => false
}
export function disableF12() {
document.addEventListener('keydown', e => {
if (e.keyCode === 123) {
e.preventDefault()
return false
}
if (e.ctrlKey && e.keyCode === 123) {
e.preventDefault()
return false
}
if (e.shiftKey && e.keyCode === 123) {
e.preventDefault()
return false
}
if (e.ctrlKey && e.shiftKey && e.keyCode === 123) {
e.preventDefault()
return false
}
})
}
export function disableCopy(cb?: () => void) {
document.addEventListener('copy', function (e) {
e.clipboardData?.setData('text/plain', '禁止复制')
e.preventDefault()
cb?.()
})
// 禁用键盘快捷键复制
document.addEventListener('keydown', e => {
if (e.ctrlKey && (e.keyCode === 67 || e.keyCode === 86 || e.keyCode === 88)) {
e.preventDefault()
cb?.()
return false
}
})
}