Right mouse click detection on SVG shape in JavaSc

2019-06-15 16:00发布


I need some help with my script in which I would like to detect RMB click.
INFO: finally I want to display my own right-click menu on a dedicated SVG shape, which is displayed with a use of Raphael js lib, I found out that there are many different examples on web, even very simple ones to implement, like with jQuery - but I have to be able to detect wether RMB was clicked or any other.
I have tried (without success on RMB) a following peace of code:

<html>
<head>
    <script type="text/javascript" src="raphael.js"></script>
    <script>
        window.onload = function() {
            var paper = new Raphael(document.getElementById('canvas_container'), 300, 300);
            var shape = paper.path('m150,150l40,0l0,20l-40,0l0,-20z');
            var fill=shape.attr({fill:'#FFFFFF'});
            fill.click(function (evt){
                if(evt.button == 2) {
                    // right mouse button pressed
                    evt.preventDefault();
                }
                alert("Pressed mouse = " + evt.button.toString());
            });
        }
    </script>
</head>

<!--    <BODY oncontextmenu="return false"> -->
<body>
    <div id="canvas_container"></div>
</body>
</html>


in IE only LMB(0) is detected, in Chrome left(0) and middle(1) and default context menu is displayed, when I disable it inside body tag (as commented-out) context menu is not displayed at all, but I still cannot get the alert with RMB(2),

thank you for all the hints/support, Borys

3条回答
趁早两清
2楼-- · 2019-06-15 16:33

Looks like SVG elements do not fire the "click" event instead they fire "contextmenu" on right click. I am using d3.js to bind the events, so this worked for me:

.on("contextmenu", function(data, index) {
     //handle right click

     //stop showing browser menu
     d3.event.preventDefault();
});
查看更多
地球回转人心会变
3楼-- · 2019-06-15 16:34

Posting the link to a good solution for d3 contextmenu here.

Github link : https://github.com/patorjk/d3-context-menu

Plunker : http://plnkr.co/edit/hAx36JQhb0RsvVn7TomS?p=preview ``

查看更多
Evening l夕情丶
4楼-- · 2019-06-15 16:50

The following jQuery context menu plugin works with D3 and SVG: https://github.com/arnklint/jquery-contextMenu

查看更多
登录 后发表回答