javascript - Detect or disable cursor movement in input field - Stack Overflow

admin2025-04-19  0

I know there are ways to position the cursor in an input field. Is there a way to detect a cursor move or preferably disable cursor movement via the arrow keys? I'm implementing an onscreen keyboard and the cursor moves left and right as the user moves left and right over the keyboard. I would like to keep the input field focused the whole time.

I know there are ways to position the cursor in an input field. Is there a way to detect a cursor move or preferably disable cursor movement via the arrow keys? I'm implementing an onscreen keyboard and the cursor moves left and right as the user moves left and right over the keyboard. I would like to keep the input field focused the whole time.

Share Improve this question edited Oct 2, 2019 at 17:35 Brian Tompsett - 汤莱恩 5,89372 gold badges61 silver badges133 bronze badges asked Mar 13, 2014 at 15:51 voodoogiantvoodoogiant 2,1586 gold badges31 silver badges53 bronze badges 3
  • 2 I think a jsfiddle would help to illustrate your case. I don't know how you're trying to implement it. – Lian Commented Mar 13, 2014 at 15:55
  • When you refer to the cursor, do you mean the mouse pointer or the flashing cursor in the text field to show where text is being inserted? – Dakotah Hicock Commented Mar 13, 2014 at 15:56
  • Thanks, useful question and 2 useful answers. But how about disabling cursor movement by the mouse? For me that is of equal concern. – Zeek2 Commented Feb 22, 2017 at 9:53
Add a ment  | 

2 Answers 2

Reset to default 4

You can attach a keydown or keyup event listener for that input, and invoke the preventDefault() method on the event object if the keyCode corresponds to cursor left and cursor right buttons. This will disable the caret movement.

yourInputElement.addEventListener('keydown', function(e){
    if(e.keyCode == 37 || e.keyCode == 39)
        e.preventDefault();
});

Here's a jQuery solution--blocks left/right arrow keys.

$([your input identifier]).keydown(function(event){
    if(event.which == 39 || event.which == 37){
        return false;
    }else{
        return true;
    }
});
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1745001321a279243.html

最新回复(0)