听右键点击 svg 元素与 Raphael.js

Listen to rightclick on svg element with Raphael.js

本文关键字:Raphael js 元素 svg 右键      更新时间:2023-09-26

当用户右键单击使用Rapahel.js创建的元素时,我需要做出响应。我读到您应该只附加一个单击事件处理程序,然后决定用户单击哪个鼠标按钮。我无法让这个工作。

<!DOCTYPE html>
<html>
<head>
<script src="http://raphaeljs.com/raphael.js"></script>
<script>
    window.onload = function() {
       var r = Raphael('demo', 640, 480);
       r.rect(10, 10, 400, 400).attr({fill: 'red'}).click(function(){
          alert('test');
       });;
    };
</script>
</head>
<body>
    <div id="demo"></div>
</body>
</html>

警报框仅在单击鼠标左键时显示。关于单击右键时如何显示警报框的任何建议?

我已经在jQuery上看到了这个小技巧:

$(r.rect(10, 10, 400, 400).attr({fill: 'red'}).node).bind('contextmenu', function(){
            alert('test');
        });

但也请阅读有关它的评论:

是的,这也有效,但仅适用于jQuery,而且最好不要使用.node, 因为 Raphael 有时会重新创建节点 - 所以你会丢失你的事件处理程序。

您可以使用

mousedown并测试e.which。这适用于FF和Chrome:

var r = Raphael('demo', 640, 480);
r.rect(10, 10, 400, 400).attr({fill: 'red'}).mousedown(function(e){
    if (e.which == 3)
        alert("hi")
});

对于跨浏览器解决方案,您可能还需要查看e.button
http://www.quirksmode.org/js/events_properties.html#button