📜  如何在 jQuery 中使用右键单击切换背景颜色?

📅  最后修改于: 2021-11-24 04:49:18             🧑  作者: Mango

在本文中,我们将学习在 jQuery 中使用右键单击来切换背景颜色。

方法一:方法是使用上下文菜单事件。 contextmenu()方法用于将contextmenu事件绑定到正在使用的元素。这可用于对正在使用的元素执行颜色切换操作。我们从绑定函数返回false以防止打开上下文菜单。

这两种背景颜色可以在两个类中定义,这些类可以使用布尔变量进行跟踪。当检测到点击时,这个变量被切换。在元素上使用addClass()removeClass()方法根据此元素添加或删除类。

jQuery代码:

let isRedBackground = true;

let box = $(".box");

box.contextmenu(function () {

  // Add and remove the background classes
  if (isRedBackground) {
    box.removeClass("redbg");
    box.addClass("greenbg");
  }
  else {
    box.removeClass("greenbg");
    box.addClass("redbg");
  }

  // Toggle the background color variable
  isRedBackground = !isRedBackground;

  return false;
});

示例:下面的示例说明了上述方法。

HTML


  

    
  
    

  

    

        GeeksforGeeks     

                How to toggle background color         using right click in jQuery?             

        Right click on the div to toggle         the color of the division     

       
    
          


HTML


  

    
      
    

  

    

        GeeksforGeeks     

                How to toggle background color         using right click in jQuery?             

        Right click on the div to         toggle the color of the division     

       
    
          


输出:

方法 2:第二种方法是使用mousedown() 事件以获得右键单击。鼠标按下() 方法用于将mousedown事件绑定到正在使用的元素。这可用于通过检查哪个来获得鼠标的右键单击 事件的属性等于“3”,表示右键单击。

无需在类中定义背景颜色,可以将两种背景颜色定义为两个变量和css() 方法可用于设置分区的背景颜色。可以使用单独的布尔变量来跟踪当前背景颜色并自动设置分区的颜色,类似于上述方法。

jQuery代码:

let isBackgroundOne = true;
let backgroundOne = "red";
let backgroundTwo = "blue";
let box = $(".box");

// Bind the mousedown event
box.mousedown(function (event) {

    // Disable the context menu
    box.contextmenu(false);

    // Check if right mouse button
    if (event.which == 3) {

        // Toggle the color based on the 
        // variable
        if (isBackgroundOne) {
            box.css({
                backgroundColor: backgroundTwo
        );
        }
        else {
            box.css({
                backgroundColor: backgroundOne
            });
        }

        // Toggle the variable itself
        isBackgroundOne = !isBackgroundOne;
    }
});

示例:下面的示例说明了上述方法。

HTML



  

    
      
    

  

    

        GeeksforGeeks     

                How to toggle background color         using right click in jQuery?             

        Right click on the div to         toggle the color of the division     

       
    
          

输出:

切换背景