首页 > 代码库 > 自定义右键菜单

自定义右键菜单

代码如下:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <style>
            html, body {
                margin: 0;
                padding: 0;
            }
            ul {
                width: 40px;
                list-style: none;
                display: inline-block;
                margin: 0;
                padding: 0;
                position: fixed;
            }
            ul li {
                padding-left: 10px;
                line-height: 20px;
                background: greenyellow;
            }
        </style>
    </head>
    <body>
        <ul id="customList">
            <li>11</li>
            <li>22</li>
            <li>33</li>
        </ul>
    </body>
    <script>
        document.oncontextmenu= function(event){
            var e= event || window.event;
            e.preventDefault? e.preventDefault():e.returnValue= http://www.mamicode.com/false;
            var customList= document.getElementById("customList");
            customList.style.left= e.clientX+ "px";
            customList.style.top= e.clientY+ "px";
        }
    </script>
</html>

解析:

document.oncontextmenu: oncontextmenu方法在目标元素上右键时触发,兼容性良好

var e= event || window.event;
e.preventDefault? e.preventDefault():e.returnValue= http://www.mamicode.com/false;

兼容IE并阻止默认行为

customList.style.left= e.clientX+ "px";
customList.style.top= e.clientY+ "px";

定位自定义的菜单

自定义右键菜单