如何使用jQuery在触发contextmenu事件时显示信息
在这篇文章中,我们将学习如何使用jQuery在触发上下文菜单事件时显示一个信息。浏览器中的上下文菜单是一个有多个选择的菜单,当用户点击右键时出现。
方法:我们将使用contextmenu事件来检查用户是否已经触发了页面上的上下文菜单。这可以通过两种方式实现。第一种是使用contextmenu()方法,监听它所使用的元素上的contextmenu事件。第二种是使用on()方法来监听contextmenu事件。然后,事件处理函数可以用来向用户显示一个信息。
语法:
$("element_selected").contextmenu(function () {
alert("Message to be displayed");
});
或者,
$("element_selected").on('contextmenu', function () {
alert("Message to be displayed");
});
例子:这个例子显示了当contextmenu事件被触发时,人们可以通过两种方式来显示信息。
<html>
<head>
<!-- Getting the jQuery library -->
<script src=
"https://code.jquery.com/jquery-git.js">
</script>
<style>
.elem1, .elem2 {
height: 50px;
border: 1px solid;
margin: 10px;
}
</style>
</head>
<body>
<h1 style="color: green;">
GeeksforGeeks
</h1>
<div class="elem1">
<p>This is element 1</p>
</div>
<div class="elem2">
<p>This is element 2</p>
</div>
<script>
// Using the contextmenu() method
// to display the message
(".elem1").contextmenu(function () {
// Display the message
alert("Element 1 message");
});
// Using the on() method to check
// for the contextmenu event
(".elem2").on('contextmenu', function () {
// Display the message
alert("Element 2 message");
});
</script>
</body>
</html>
输出:写下对任何div的点击。