【问题标题】:Disable mouse right click and don't change cursor position In Javascript禁用鼠标右键单击并且不要在Javascript中更改光标位置
【发布时间】:2014-05-16 22:45:04
【问题描述】:

我想禁用鼠标右键单击并且不要在 Javascript 中更改光标位置。这是我的代码示例:

<input id="PhoneNumber" style="width: 160px;" />

$('#PhoneNumber').mousedown(function (e) {
    if (event.which > 1) {
        e.preventDefault();
    } else {
        //Do some work
    }
});

但这不起作用。当我用鼠标右键单击时,它会改变插入符号的位置。

[更新] 适用于铬。无法在 IE 上运行

【问题讨论】:

  • 适用于 chrome。无法在 IE 上运行

标签: javascript jquery html input mouse


【解决方案1】:

您还需要订阅 mouseup 事件:

$('#PhoneNumber').on('mousedown mouseup', function (e) {
        if (event.which > 1) {
            e.preventDefault();
        } else {
            //Do some work
        }
    });

【讨论】:

  • @ArmenMkrtchyan 哪个版本的 IE?
【解决方案2】:

你应该使用 contextmenu 事件并返回 false:

    $('#PhoneNumber').on("contextmenu", function(e) {
        return false;
    });

【讨论】:

    【解决方案3】:

    你可以使用contextmenu:

    $('#PhoneNumber').contextmenu(function (e) {
          e.preventDefault();
    });
    

    Working Demo

    【讨论】:

    • 在那个演示中光标改变了它的位置
    • @ArmenMkrtchyan:我认为你做不到。这是文本框的默认行为。
    【解决方案4】:
    $('#PhoneNumber').bind("cut copy paste contextmenu", function (e) {
                e.preventDefault();
                var pos = ($(this).getCursorPosition());
                var index = $('#PhoneNumber').val().length;
                if (index < 5) {
                    index = 5;
                }
                $(this).caretTo(index);
            });
    
            $('#PhoneNumber').click(function () {
                var pos = ($(this).getCursorPosition());
                var index = $('#PhoneNumber').val().length;
                if (index < 5) {
                    index = 5;
                }
                $(this).caretTo(index);
            });
    
            $('#PhoneNumber').on('mousedown mouseup', function (e) {
                if(event.which!=1) {
                    e.preventDefault();
                    e.returnValue = false;
                }
            });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多