天天看點

阻止預設時間

demo:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        .box{width:200px;height: 300px;background: #ccc;position: absolute;left:0;top:0;display: none}
        .box ul{margin: 0}
    </style>
</head>
<body>
    <!-- <a href="http://www.baidu.com">21321312</a> -->
    <div class="box">
        <ul>
            <li>選項1</li>
            <li>選項2</li>
            <li>選項3</li>
            <li>選項4</li>
        </ul>
    </div>
</body>
<script>
    var obox = document.querySelector(".box")
    document.oncontextmenu = function(eve){   //oncontextmenu 事件在元素中使用者右擊滑鼠時觸發并打開上下文菜單。
        var e = eve || window.event;
        obox.style.display = "block";
        
        // return false;

        // 取消預設事件
        stopDefault(e);

        obox.style.left = e.offsetX + "px";
        obox.style.top = e.offsetY + "px";
    }

    document.onclick = function(){
        obox.style.display = "none"
    }

    function stopDefault(e){
        if(e.preventDefault){
            e.preventDefault()  //IE
        }else{
            e.returnValue = false;  //GOOGLE
        }
    }   //封裝函數



</script>
</html>