Chrome,Opera和IE(javascript)中的右击事件(onclick)

时间:2010-08-22 20:46:36

标签: javascript internet-explorer javascript-events google-chrome opera

在Firefox中

我使用了document.onclick事件,然后检查它是否是右键单击,如果我右键单击,一切都按预期进行。但是在Chrome,Opera和IE8中,如果我右键单击document.onclick不会触发。

我想为img元素提供自定义上下文菜单。我该怎么做?

1 个答案:

答案 0 :(得分:7)

右键单击调用大多数标准浏览器中的上下文菜单;因此,您可以使用“oncontextmenu”侦听器来处理右键单击事件。如果您不希望在调用JS代码后显示标准浏览器上下文菜单,则侦听器应返回false。

以下是一些处理图像左右键点击的示例html。

<html>
<head>
    <script type="text/javascript">
        function handleRightClick() {
            alert("Got right click!");
        };

        function handleLeftClick() {
            alert("Got left click!");
        };
    </script
</head>
<body>
    <img src="http://thefuturebuzz.com/pics/the-matrix.jpg" onclick="handleLeftClick(this);" oncontextmenu="handleRightClick(this); return false;" />
</body>
</html>

有关详细信息,请查看http://www.w3schools.com/html5/html5_ref_eventattributes.asp