Home > Article > Web Front-end > jQuery custom element right click event
This article mainly brings you a jQuery custom element right-click event (implementation case). The editor thinks it’s pretty good, so I’ll share it with you now and give it as a reference. Let’s follow the editor to take a look, I hope it can help everyone.
In most cases we use the left click to interact with the page, and the right click is mostly for developers to review elements. Sometimes we also need to customize the right click behavior of the mouse to achieve better results. Interactivity, common comics include left-clicking to advance and right-clicking to go back.
The first step is to block the default right-click behavior of the browser, that is, to prevent pop-up boxes.
First, bind the pop-up blocking function to the target element:
//阻止浏览器默认右键点击事件 $("p").bind("contextmenu", function(){ return false; })
In this way, the right-click event of the p element will be blocked, while other areas of the browser will not be affected. If you want to block right-click events on the entire page, just do this:
document.oncontextmenu = function() { return false; }
Next, you can bind the right-click response function to the element:
$("p").mousedown(function(e) { console.log(e.which); //右键为3 if (3 == e.which) { $(this).css({ "font-size": "-=2px" }); } else if (1 == e.which) { //左键为1 $(this).css({ "font-size": "+=3px" }); } })
The example effect is the right-click font Zoom out, left-click to make the font larger, and other areas can respond to the default right-click event.
Complete code:
<head> <style type="text/css"> p{ font-size:20px; } </style> <script src="../jquery.js"></script> <script> $(function() { //阻止浏览器默认右键点击事件 /*document.oncontextmenu = function() { return false; }*/ //某元素组织右键点击事件 $("p").bind("contextmenu", function(){ return false; }) $("p").mousedown(function(e) { console.log(e.which); //右键为3 if (3 == e.which) { $(this).css({ "font-size": "-=2px" }); } else if (1 == e.which) { //左键为1 $(this).css({ "font-size": "+=3px" }); } }) }) </script> </head> <body> <p> p </p> </body>
Related recommendations:
jQuery's method of detecting left and right mouse clicks_jquery
ztree of jquery implements right-click collection function
The above is the detailed content of jQuery custom element right click event. For more information, please follow other related articles on the PHP Chinese website!