How to add a custom right-click menu to a webpage?

后端 未结 19 1523
广开言路
广开言路 2020-11-22 15:54

I want to add a custom right-click menu to my web application. Can this be done without using any pre-built libraries? If so, how to display a simple custom right-click menu

19条回答
  •  一整个雨季
    2020-11-22 16:08

    I use something similar to the following jsfiddle

    function onright(el, cb) {
        //disable right click
        document.body.oncontextmenu = 'return false';
        el.addEventListener('contextmenu', function (e) { e.preventDefault(); return false });
        el.addEventListener('mousedown', function (e) {
            e = e || window.event;
            if (~~(e.button) === 2) {
                if (e.preventDefault) {
                    e.preventDefault();
                } else {
                    e.returnValue = false;
                }
                return false;
            }
        });
    
        // then bind Your cb
        el.addEventListener('mousedown', function (e) {
            e = e || window.event;
            ~~(e.button) === 2 && cb.call(el, e);
        });
    }
    

    if You target older IE browsers you should anyway complete it with the ' attachEvent; case

提交回复
热议问题