jQuery-*:not()不排除元素 [英] jQuery - *:not() not excluding elements

查看:113
本文介绍了jQuery-*:not()不排除元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的目标是禁用除<kbd><textarea>标记之外的所有位置的右键单击.我正在使用*:not(kbd,textarea)排除禁用右键单击-.on('contextmenu', function(e){ e.preventDefault(); });.假定我可以右键单击<kbd><textarea>标记,但不能.很疲惫.

My goal is to disable right-click everywhere except <kbd> and <textarea> tags. I am using *:not(kbd,textarea) to exclude disabling right-click - .on('contextmenu', function(e){ e.preventDefault(); });. It is supposed that I can right click on <kbd> and <textarea> tags but I cannot. It is werid.

$(document).ready(function(){
  $('*:not(kbd,textarea)').on('contextmenu', function(e){
      e.preventDefault();
  });
});

div {
  width: 170px;
  height: 170px;
  background-color: green;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<kbd>right click me</kbd>
<textarea>right click me</textarea>
can't right click me
</div>

推荐答案

要明确:*:not(kbd,textarea)正常工作.问题与浏览器如何处理事件有关.

To be clear: *:not(kbd,textarea) works just fine. The problem has to do with how events are processed in browsers.

大多数事件都会冒出来, contextmenu也会这样做.由于<kbd><textarea>元素位于<div>内部,因此绑定到<div>的事件处理程序将始终取消contextmenu事件.

Most events bubble up, contextmenu does as well. Since the <kbd> and <textarea> elements are inside the <div>, the event handler bound to the <div> will always cancel the contextmenu event.

根据您的确切用例,您可以简单地检查事件是否起源于元素本身,并仅在这种情况下才阻止它:

Depending on your exact use case, you could simply check whether the event originated on the element itself and only prevent it in that case:

$(document).ready(function(){
  $('*:not(kbd,textarea)').on('contextmenu', function(e){
      if (this === e.target) {
        e.preventDefault();
      }
  });
});

div {
  width: 170px;
  height: 170px;
  background-color: green;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<kbd>right click me</kbd>
<textarea>right click me</textarea>
can't right click me
</div>

但是,不要将处理程序绑定到每个元素,而要使用事件委托.将处理程序绑定到文档的根目录,并检查事件的来源:

However, instead of binding the handler to every element, use event delegation. Bind the handler to the root of the document and check where the event originates from:

$(document).ready(function(){
  $('body').on('contextmenu', function(e){
      if (!$(e.target).is('kbd,textarea')) {
        e.preventDefault();
      }
  });
});

div {
  width: 170px;
  height: 170px;
  background-color: green;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<kbd>right click me</kbd>
<textarea>right click me</textarea>
can't right click me
</div>

这篇关于jQuery-*:not()不排除元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆