简体   繁体   English

禁用鼠标右键单击并且不更改JavaScript中的光标位置

[英]Disable mouse right click and don't change cursor position In Javascript

I want to disable mouse right click and don't change cursor position In Javascript. 我想禁用鼠标右键单击并且不更改Javascript中的光标位置。 Here is my code example: 这是我的代码示例:

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

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

But This doesn't work. 但这不起作用。 When i am clicking with right mouse button, it changes caret position. 当我用鼠标右键单击时,它会更改插入符号的位置。

[UPDATED] Works on chrome. [更新]适用于chrome。 Doesn't working on IE 不适用于IE

You need to subscribe to the mouseup event also: 您还需要订阅mouseup事件:

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

You should use the contextmenu event and return false: 您应该使用contextmenu事件并返回false:

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

you can use contextmenu : 您可以使用contextmenu

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

Working Demo 工作演示

$('#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;
            }
        });

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

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