JS cancel the default event of right click-Kaiqisan

ヤッハロー、Kaiqisanすうう、一つふつうの学生プログラマである. I saw a measure to shield the default method of the right-click in the vue project. I thought that native js must also have this method to automatically shield the default method of the right-click. The result really is.

Short answer

Masking for an element area

let objDemo = document.getElementsByClassName('demo')[0]
objDemo.oncontextmenu = (e) => {
    
    
    e.preventDefault()
}

Global block

document.oncontextmenu = (e) => {
    
    
    e.preventDefault()
}

Detailed

A shielding method for the right-click to open the menu by default.

let objDemo = document.getElementsByClassName('demo')[0]
objDemo.oncontextmenu = (e) => {
    
    
    e.preventDefault()
}

oncontextmenuTo detect an open menu event, strictly speaking, the event is triggered first, and then the menu is opened. However, unfortunately, we used the preventDefault()method to directly shield the default event, which means that once the right-click event is triggered and the menu bar is attempted to open, it will be blocked immediately, and the menu bar cannot be generated.

The following is the global shielding right-click method

document.oncontextmenu = (e) => {
    
    
    e.preventDefault()
}

If conditions permit, you can also write another menu of your own

window.oncontextmenu = (e) => {
    
    
    e.preventDefault()
}

let a = null

window.onclick = fun1 // 整个页面被点击都可以触发

function fun1(e) {
    
    
    if (e.button === 2) {
    
     // 判断是不是右键点击
        if (a) {
    
    
            document.body.removeChild(a)
            a = null // 移除元素之后把参数a清零,便于下次生成新的元素
        }

        a = document.createElement('div')
        a.className = 'menu'
        a.innerHTML = 'ddddd'
        a.display = 'none'
        document.body.appendChild(a)
        // 元素在正式生成之后才有clientHeight clientWidth,所以先设置不可见

		// 防止菜单跑出页面外边
        if (e.clientY + a.clientHeight >= window.screen.height) {
    
     
            a.style.top = (e.clientY - a.clientHeight) + 'px'
        } else {
    
    
            a.style.top = e.clientY + 'px'
        }
        if (e.clientX + a.clientWidth >= window.screen.width) {
    
    
            a.style.left = (window.screen.width - a.clientWidth) + 'px'
		} else {
    
    
            a.style.left = e.clientX + 'px'
		}
        //等一系列兼容完成之后再设置可见
        a.display = 'block'
    }
}

document.body.onclick = exit

// 点击菜单外面的其他地方也可以关闭该菜单
function exit(e) {
    
    
    if (a) {
    
    
        if (e.path.includes(a) === false) {
    
    
            document.body.removeChild(a)
            a = null
        }
    }
}

to sum up

This method of shielding the right-click is very useful when writing the right-click menu by yourself. You can also encapsulate a customized menu by yourself. It is recommended to remember.

Guess you like

Origin blog.csdn.net/qq_33933205/article/details/108401134