網頁自定義右鍵菜單

很簡單代碼如下:

<!DOCTYPE html>
<html>
<head>
    <title>右鍵菜單</title>
    <style type="text/css">
        #right-menu{
            position: absolute;
            width: 200px;
            height: auto;
            border: 1px #ccc solid;
            display: none;
            padding:2px 0; 
            box-shadow: 5px 5px 5px #ccc;
        }
        .menu-item{
            height: 25px;
            margin:4px 0; 
            padding:0 10px;
            cursor: pointer;
        }
        .menu-item:hover{
            background-color: #ccc;
        }
        .menu-item-separator{
            border-top:1px #ccc solid;
            height: 1px;
        }
    </style>
</head>
<body>

<!-- 自定義右鍵菜單dom -->
<div  id="right-menu">
    <div class="menu-item">執行</div>
    <div class="menu-item">啓動</div>
    <div class="menu-item-separator"></div>
    <div class="menu-item">刪除</div>
    <div class="menu-item">導出</div>
</div>
    <script type="text/javascript">
        window.oncontextmenu = function(e){
            e.preventDefault(); //阻止瀏覽器自帶的右鍵菜單顯示
            var menu = document.getElementById("right-menu");
            menu.style.display = "block"; //將自定義的“右鍵菜單”顯示出來
            menu.style.left = e.clientX + "px";  //設置位置,跟隨鼠標
            menu.style.top = e.clientY+"px"; 
        }
        window.onclick = function(e){ //點擊窗口,右鍵菜單隱藏
            var menu = document.getElementById("right-menu");
            menu.style.display = "none";
        }
    </script>
</body>
</html>

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章