Home >Web Front-end >Front-end Q&A >How to hide the right click in javascript

How to hide the right click in javascript

藏色散人
藏色散人Original
2022-01-11 15:08:121823browse

How to hide the right-click in javascript: 1. Open the corresponding code file; 2. Use the "window.oncontextmenu=function(e){e.preventDefault();}" method to disable the right-click menu.

How to hide the right click in javascript

The operating environment of this article: Windows 7 system, javascript1.8.5, Dell G3 computer.

How to hide the right click in javascript?

js Set or disable the right mouse button menu

When the user clicks the right mouse buttononcontextmenuThe event is triggered

js disable mouse right-click menu

window.oncontextmenu=function(e){
    //取消默认的浏览器自带右键 很重要!!
    e.preventDefault();
}

js customize mouse right-click menu

html prepare custom menu items

<div id="menu">
            <div class="menu">功能1</div>
            <div class="menu">功能2</div>
            <div class="menu">功能3</div>
            <div class="menu">功能4</div>
            <div class="menu">功能5</div></div>

css sets menu item style

#menu{
    width: 0; /*设置为0 隐藏自定义菜单*/
    height: 125px;
    overflow: hidden; /*隐藏溢出的元素*/
    box-shadow: 0 1px 1px #888,1px 0 1px #ccc;
    position: absolute; /*自定义菜单相对与body元素进行定位*/
}
.menu{
    width: 130px;
    height: 25px;
    line-height: 25px;
    padding: 0 10px;
}

js controls the display and hiding of menu

window.oncontextmenu=function(e){
    //取消默认的浏览器自带右键 很重要!!
    e.preventDefault();
    //获取我们自定义的右键菜单
    var menu=document.querySelector("#menu");
    //根据事件对象中鼠标点击的位置,进行定位
    menu.style.left=e.clientX+'px';
    menu.style.top=e.clientY+'px';
    //改变自定义菜单的宽,让它显示出来
    menu.style.width='100px';
    menu.style.height='auto';
}
//鼠标左键任意位置单击, 关闭右键菜单
window.onclick=function(e){
    //用户触发click事件就可以关闭了,因为绑定在window上,按事件冒泡处理,不会影响菜单的功能
    document.querySelector('#menu').style.height=0;
}

Recommended study: "js basic tutorial"

The above is the detailed content of How to hide the right click in javascript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn