简体   繁体   English

右键单击添加/删除课程

[英]Add/remove class on right click

I'm trying to add a class on right-click of an element and then remove it when anything else on the page is clicked. 我试图在元素的右键单击上添加一个类,然后在单击页面上的其他任何内容时将其删除。

I'm using jQuery. 我正在使用jQuery。

My function is this so far: 到目前为止,我的职能是:

$(".classElement").live('mousedown', function(e) { 
   if( (e.which == 3) ) {
     $(".classElement").addClass("active");
   }
   e.preventDefault();
}).live('contextmenu', function(e){
 e.preventDefault();
});

However, this adds the "active" class to all ".classElement" in the doc, rather than the individual one being clicked. 但是,这会将“活动”类添加到文档中的所有“ .classElement”中,而不是单击单个类。 I want to only add the class to the element being clicked. 我只想将类添加到要单击的元素中。

Also, how can I remove the class when anything else is clicked? 另外,单击其他任何按钮时如何删除该类?

You can removClass active on click of body element, but for this you have to stop event propagation when you are clicking on current element. 您可以在单击body元素时激活removClass,但是为此,您必须在单击当前元素时停止事件传播。

$(document).on('mousedown','.classElement', function(e) { 
  e.preventDefault();
  if( (e.which == 3) ) {
    $(this).addClass("active");
  }
  e.stopPropagation();
}).on('contextmenu','.classElement', function(e){
  e.preventDefault();
});
$(document.body).click(function(){
  $(".classElement").removeClass("active");
});

You can use $(this) to target current clicked element, so you can do: 您可以使用$(this)定位当前单击的元素,因此可以执行以下操作:

$(this).addClass("active");

instead of: 代替:

$(".classElement").addClass("active");

Also, since .live() was removed since version 1.9 , you should use .on() instead. 另外,由于从1.9版删除了.live() ,因此应该改用.on()

to target specific element: 针对特定元素:

$(this).addClass("active");

and to remove it when anything else is clicked, add this: 并在单击其他任何内容时将其删除,请添加以下内容:

$(window).one("click", function(){
   $(this).removeClass("active");
});

This adds a one time only click event listener to the window. 这会将一次性单击事件侦听器添加到窗口。

Use this code 使用此代码

$(".classElement").live('contextmenu', function(e){ e.preventDefault(); if( (e.which == 3) ) { $(this).addClass("active"); } }); and then remove class on document click 然后删除文档上的类,单击

$(document).click(function(){ $(".classElement").removeClass("active"); });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM