使用Raphael.js监听SVG元素上的右键单击事件

11

我需要在使用 Raphael.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有时会重新创建节点 - 因此您会失去事件处理程序。

1个回答

11

你可以使用mousedown并测试e.which。 这适用于Firefox和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


谢谢。当你知道答案时,它们似乎是如此简单 :) - John

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接