总有人间一两风,填我十万八千梦

jQuery .contextmenu() 用法 手册 | 示例代码

jQuery开发手册 归档 361℃ 0评论

Description: Bind an event handler to the "contextmenu" JavaScript event, or trigger that event on an element.

  • version added: 1.0.contextmenu( handler )

    • handler
      Type: Function( Event eventObject )
      A function to execute each time the event is triggered.
  • version added: 1.4.3.contextmenu( [eventData ], handler )

    • eventData
      Type: Anything
      An object containing data that will be passed to the event handler.
    • handler
      Type: Function( Event eventObject )
      A function to execute each time the event is triggered.
  • version added: 1.0.contextmenu()

    • This signature does not accept any arguments.

This method is a shortcut for .on( "contextmenu", handler ) in the first two variations, and .trigger( "contextmenu" ) in the third. The contextmenu event is sent to an element when the right button of the mouse is clicked on it, but before the context menu is displayed. In case the context menu key is pressed, the event is triggered on the html element. Any HTML element can receive this event. For example, consider the HTML:

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

The event handler can be bound to the <div> as follows:

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

Now right-clicking on this element displays the alert:

Handler for .contextmenu() called.

To trigger the event manually, call .contextmenu() without an argument:

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

Additional Notes:

  • As the .contextmenu() method is just a shorthand for .on( "contextmenu", handler ), detaching is possible using .off( "contextmenu" ).

Examples:

To show a "Hello World!" alert box when the contextmenu event is triggered on a paragraph on the page:

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

Right click to toggle background color.

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>

转载请注明:悠然品鉴 » jQuery .contextmenu() 用法 手册 | 示例代码

喜欢 (0)or分享 (0)
发表我的评论
取消评论

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址