[英]How can I turn right click off and on using functions in JS?
I have disabled right click in my application using the following: 我已使用以下命令在应用程序中禁用了右键单击:
<body oncontextmenu="return false;">
I have a textarea element which has spellcheck enabled. 我有一个启用了拼写检查的textarea元素。 I want to be able to right-click in this field (for spellcheck) but I want right-click to be disabled everywhere else in the app.
我希望能够在此字段上单击鼠标右键(进行拼写检查),但是我希望右键单击在应用程序的其他任何地方都被禁用。
I have done the following: 我已经完成以下工作:
<textarea onfocus="rightclickon()" onblur="rightclickoff()" spellcheck="true"></textarea>
These are the functions: 这些是功能:
function rightclickon() {
$('body').prop('oncontextmenu', 'null');
}//end rightclickon
function rightclickoff() {
$('body').prop('oncontextmenu', 'return false');
}//end rightclickoff
My logic behind the above is that whenever the user enters the textarea, right-click would be enabled but when they leave the field, it would be disabled again. 我上面的逻辑是,每当用户输入文本区域时,将启用右键单击,但是当他们离开该字段时,将再次禁用它。 This does not work how I expected.
这不符合我的预期。
The first part works (right-click is enabled when the ueser enters the field). 第一部分起作用(当用户输入字段时,启用右键单击)。 However, when the field is left, right-click does not get disabled again.
但是,在保留该字段时,不会再次禁用右键单击。 It just remains on.
它仍然存在。
Is their an easier way to achieve what I want? 他们是实现我想要的更简单的方法吗?
Simply inspect the origin of the event and decide what to do accordingly 只需检查事件的起源并决定相应的操作
document.addEventListener('contextmenu', function(e) { if (!e.target.matches('textarea')) { e.preventDefault() } }, false)
<p>Some paragraph</p> <ul> <li>List 1</li> <li>List 2</li> <li>List 3</li> </ul> <textarea>Just try right-clicking in here</textarea> <p>Another paragraph</p>
See https://developer.mozilla.org/en/docs/Web/API/Element/matches for details about Element.matches
有关
Element.matches
详细信息,请参见https://developer.mozilla.org/en/docs/Web/API/Element/matches
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.