【问题标题】:How to jquery add class to div on Rightclick [duplicate]如何在右键单击时将类添加到 div [重复]
【发布时间】:2014-12-04 09:38:05
【问题描述】:

左键点击

$(document).ready(function(){
    $( "div" ).click(function() {
      $( this ).toggleClass( "class-one" );
     //alert('left click');
    });
});

右键点击

$(document).ready(function(){
    $( "div" ).click(function() {
      $( this ).toggleClass( "class-two" );
     //alert('Right Click');
    });
});

这是我的要求 Jquery 鼠标左键单击添加一个类,鼠标右键单击添加另一个类,所以我的任务左键单击添加类完成,右键单击添加类不起作用,

如果可以的话右击 Jquery ?

【问题讨论】:

标签: jquery html css


【解决方案1】:

这样做:

HTML --

<div id="test">
    test test
</div>

CSS --

div {
    width: 300px;
    height: 200px;
    background-color: #99EAEA;
}

.class-one {
    background-color: #EAEAEA;
}

.class-two {
    background-color: #EA3355;
}

JQUERY --

$(document).ready(function(){ 
    document.oncontextmenu = function() { return false; };

    $("#test").click(function() {
      $( this ).removeClass("class-two").addClass("class-one");
    });

    $(document).mousedown(function(e){ 
        if( e.button == 2 ) { 
            $("#test").removeClass("class-one").addClass("class-two");
            return false; 
        } 
        return true; 
    });  
});

就是这样!演示:http://jsfiddle.net/ag62dyry/1/

【讨论】:

  • 这是正确的答案,我再次使用它,所以再次出现一个问题窗口右键单击不起作用,
【解决方案2】:

你可以试试这个:

$(document).ready(function () {
    $("div").mousedown(function (e) {
        $(this).toggleClass("class-two");
        if (e.button == 2) {
            alert('Right mouse!');
            //here goes the code you want to add in mouse right click
        }
    });
});
div {
    height:100px;
    width: 100px;
    background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div></div>

【讨论】:

    【解决方案3】:

    右键事件名称为contextmenu:

    $("div").on("contextmenu", function() {
        $(this).toggleClass("class-two");
    });
    

    【讨论】:

    • 是的,这是 jQuery 1.7+ 的正确方式。 PS你忘了结束)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-17
    • 1970-01-01
    • 1970-01-01
    • 2012-09-01
    • 1970-01-01
    • 2017-10-31
    相关资源
    最近更新 更多