Jquery to achieve human options to disable the right mouse button

  • 2020-03-30 03:28:10
  • OfStack

The use of more violent means to disable the right mouse button is not human, so it is best to selectively disable the right mouse button.

The code example is as follows:


<!DOCTYPE html> <html> 
<head> 
<meta charset="utf-8"> 
<meta name="author" content="http://www.45it.com/" /> 
<title> The home of the script </title> 
<style type="text/css">
html,body{height:100%}
div{
width:150px;
height:50px;
background:#CCC;
}
</style>
<script type="text/javascript" src="mytest/jQuery/jquery-1.8.3.js"></script>
<script type="text/javascript"> 
$(document).ready(function(){
function jQuery_isTagName(ev,arr){
ev=$.event.fix(ev);
var target=ev.target||ev.srcElement;
if(arr&&$.inArray(target.tagName.toString().toUpperCase(),arr)==-1){
return false;
}
return true;
}

$(document).bind("contextmenu",function(ev){
if(!jQuery_isTagName(ev,['INPUT','TEXTAREA'])){
ev.preventDefault();
return false;
}
return true;
})
})
</script> 
</head> 
<body>
<div id="thediv"></div> 
<textarea></textarea>
</body> 
</html>

The above code to achieve our requirements, the following code implementation process to do a brief introduction.

Code comments:

$(document).ready(function(){}), when the text structure is fully loaded to execute the function code.
Function jQuery_isTagName(ev,arr){}, this function can determine whether the element can be used in the right menu column, the first parameter is the event object, the second parameter is an array, the array element is can be used right menu label name.
3. Ev =$.event.fix(ev), which makes the event object compatible with each browser.
Var target=ev.target|| ev.srcelement, gets the event source object.
5. If (arr && $. InArray (target. TagName. The toString (). The toUpperCase (), arr) = = 1) {return false. }, determines whether the specified tag element is in the array, and returns false if the specified tag is not in the array.
6. Return true.
$(document).bind("contextmenu",function(ev){}) registers the contextmenu event handler for the document.
9. The if (! JQuery_isTagName (ev, [' INPUT ', 'TEXTAREA'])) {
Ev. The preventDefault ();
Return false;
}
If if the specified tag is not can use right-click menu list, then use ev. The preventDefault () to stop event bubbling, this is very important, otherwise if there is a nested element, although child elements to disable the right-click menu, but the right child elements, will popup right-click menu, because the event passed to the parent element, return false can also disable the right-click menu


Related articles: