自定义右键菜单

阻止事件的默认行为

<!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>自定义右键菜单</title>
    <style>
        *{
            margin: 0;
            padding: 0;
        }
        #box{
            width: 200px;
            height: 600px;
            border: 1px solid #f00;
            display:none;
            position: absolute;

        }
        #list li{
            list-style: none;
            width: 200px;
            height: 100px;
            text-align: center;
            line-height: 100px;
            background: #eee;
            border: 1px solid #000;
        }
    </style>
</head>
<body>
    <input type="text" id="inp">
    <div id="box">
        <ul id="list">
            <li>说多了几分</li>
            <li>说多了几分</li>
            <li>说多了几分</li>
            <li>说多了几分</li>
            <li>说多了几分</li>
        </ul>
    </div>
</body>
<script>
    var box = document.getElementById('box');
    var lis = document.querySelectorAll( 'li');
    var inp = document.querySelector('input');
    // console.log( inp.value )
    document.oncontextmenu = function( eve ){
        var e = eve || window.event;
        stop ( e );
        box.style.display = 'block';
        box.style.left = e.clientX +'px';
        box.style.top = e.clientY +'px';
    }
    document.onclick = function(){
        box.style.display = 'none';
    }
    for( var i = 0 ; i < lis.length; i++){
        lis[i].onmouseover = function(){
            this.style.background = '#f66';
        }
        lis[i].onmouseout = function(){
            this.style.background =  "";
        }
        lis[i].onclick= function(){
            inp.value = this.innerHTML;
        }
    }
    function stop( e ){
        if( e.preventDafualt ){
            e.preventDefault();
        }else{
            window.event.returnValue = false;
        }
    }
</script>
</html>
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容