欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

17.JavaScript实现鼠标右键自定义菜单

程序员文章站 2022-07-06 10:11:21
JavaScript实现鼠标右键自定义菜单:

javascript实现鼠标右键自定义菜单:

<!doctype html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>document</title>
    <style>
        .area1 {
            width: 200px;
            height: 200px;
            border: 1px solid #ccc;
            float: left;
            background: #008c8c
        }

        .area2 {
            width: 200px;
            height: 200px;
            border: 1px solid #ccc;
            float: right;
            background: #008c8c
        }

        .contain-text {
            position: fixed;
            left: 300px;
            top: 300px;
            border: 1px solid #ccc;
            background:#fff;
            display: none;
            padding:10px;
            text-align:left;
        }

        .contain-text ul {
            list-style: none;
            margin:0;
            padding:0;
        }
    </style>
</head>

<body>
    <div class="area1">
    </div>
    <div class="area2">
    </div>

    <div class="contain-text">
        <ul>
            <li>菜单1</li>
            <li>菜单2</li>
            <li>菜单3</li>
            <li>菜单4</li>
            <li>菜单5</li>
            <li>菜单6</li>
            <li>菜单7</li>
            <li>菜单8</li>
            <li>菜单9</li>
            <li>菜单10</li>
        </ul>
    </div>
    <script>
        var div1 = document.queryselector(".area1");
        var div2 = document.queryselector(".area2");
        var menu = document.queryselector(".contain-text");//菜单
        //注册自定义鼠标右键菜单事件
        div1.oncontextmenu = div2.oncontextmenu = function (e) {
            e.preventdefault();
            menu.style.display = "block";
            console.log(e.clientx, e.clienty);
            menu.style.left = e.clientx + "px";
            menu.style.top = e.clienty + "px";
        }

        window.onmousedown = function(){
            menu.style.display = "none";
        }
    </script>
</body>

</html>

效果展示:

17.JavaScript实现鼠标右键自定义菜单