JS鼠标右键自定义列表

html

<div id="menu">
    <a href="javascript:;">a</a>
    <a href="javascript:;">b</a>
    <a href="javascript:;">c</a>
    <a href="javascript:;">d</a>
</div>

css

#menu{
        background-color: #fff;
        width: 300px; 
        box-shadow: 0 1px 20px #eeeeee,1px 0 20px #eeeeee;
        position: absolute;
        z-index: 99999;
        -webkit-border-radius: 6px;
        -moz-border-radius: 6px;
        border-radius: 6px;
        overflow: hidden;
        -webkit-box-sizing: border-box;
        -moz-box-sizing: border-box;
        box-sizing: border-box;
    }
    #menu a{
        display: block;
        height: 40px;
        line-height: 40px;
        padding: 0 20px;
        text-decoration:none;
        font-size: 14px;
        color: #4c4c4c;
        -webkit-box-sizing: border-box;
        -moz-box-sizing: border-box;
        box-sizing: border-box;
    }
    #menu a:hover{
        background-color:#eeeeee;
    }

js

window.oncontextmenu = function (e) {
    var e = event || window.event;
    //取消默认浏览器自带右键
    e.preventDefault();
    //获取自定义右键菜单
    let menu = document.getElementById('menu');

    //根据事件对象中鼠标点击的位置,进行定位
    menu.style.left = e.clientX + 'px';
    menu.style.top = e.pageY + 'px';
    
    //改变自定义菜单宽度。让其显示
        menu.style.display = 'block';
}

//close右键菜单
window.onclick = function (e) {
    //触发click事件即可关闭
    document.getElementById('menu').style.display = "none";
}

你可能感兴趣的:(js)