Check if INSERT mode is ON when typing in an input

前端 未结 2 1237
名媛妹妹
名媛妹妹 2021-01-19 05:35

I\'m trying to calculate the value of an input field on various events regardless of the event caught.

I\'m taking into account the events keypress keyup keydow

相关标签:
2条回答
  • 2021-01-19 05:42

    For IE only:

    document.queryCommandValue("OverWrite");
    

    As far as I know, Firefox and Chrome don't have overwrite mode. The insert key doesn't work in those browsers, and they are always in insert mode.

    Moreover, Mac keyboard doesn't have a insert key from the beginning. So Safari also is always in insert mode.

    0 讨论(0)
  • 2021-01-19 06:05

    Although I don't think you can directly access the state of the user's Insert status, you can figure out how long the strings are when the user is editing the field.

    Consider this, tied with a simple <input id="input" />:

    var i = document.getElementById('input');
    
    document.onkeydown = function(e) {
        var c = String.fromCharCode(event.keyCode);
    
        if(null !== c.match(/\w/)) {
            l = i.value.length;
        }
    }
    
    document.onkeyup = function(e) {
        var c = String.fromCharCode(event.keyCode);
    
        if(null !== c.match(/\w/)) {
            if(l === i.value.length) {
                console.log("Keyboard insert might be off - length hasn't changed");
            }
        }
    }
    

    Note that there is a rudimentary check to try and isolate only letters and numbers (with the match against the keyCode (borrowed from here), as you don't want to perform the check against a shift key being pressed, for instance.

    Basic POC here: http://jsfiddle.net/Xp3Jh/

    I'm certain there are more in-depth checks you can do, but hopefully this helps!

    0 讨论(0)
提交回复
热议问题