.contextmenu()

.contextmenu( handler )返回类型:jQuery

描述:把一个事件处理函数绑定到“contextmenu”JavaScript事件上,或者在一个元素上触发该事件。

此方法在前两种变体中是.on( "contextmenu", handler )的简写,在第三种变体中是.trigger( "contextmenu" )的简写。 当鼠标右击在元素上单击、显示上下文菜单这,contextmenu事件发送到该元素。万一是上下文菜单键按下了,事件是在html元素上触发的。任何HTML元素都可以接受此事件。 例如:考虑下面的HTML:

1
2
3
<div id="target">
Right-click here
</div>

事件处理函数可以如下绑定到<div>

1
2
3
$( "#target" ).contextmenu(function() {
alert( "Handler for .contextmenu() called." );
});

右键单击元素以显示警告:

Handler for .contextmenu() called.

若要手工触发事件,请不带参数地调用.contextmenu()

1
$( "#target" ).contextmenu();

补充说明:

  • 因为.contextmenu()方法是.on( "contextmenu", handler )的简写,所以可以使用.off( "contextmenu" )来分离它。

示例:

当网页上的段落上触发contextmenu事件时,显示“Hello World!”警告框。

1
2
3
$( "p" ).contextmenu(function() {
alert( "Hello World!" );
});

右击以切换背景色。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>contextmenu demo</title>
<style>
div {
background: blue;
color: white;
height: 100px;
width: 150px;
}
div.contextmenu {
background: yellow;
color: black;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<div></div>
<span>Right click the block</span>
<script>
var div = $( "div:first" );
div.contextmenu(function() {
div.toggleClass( "contextmenu" );
});
</script>
</body>
</html>

演示: