Javascript keycode clash: “right arrow” and “single quote”

后端 未结 4 1204
伪装坚强ぢ
伪装坚强ぢ 2021-01-14 07:06

The following script does what it should, that is, it reacts on the keys \"arrow left\" and \"arrow right\". However, due to a keycode clash, it reacts on a single quote as

4条回答
  •  -上瘾入骨i
    2021-01-14 07:51

    As it is a text input, it seems you'd also have a problem when someone is trying to use the arrow keys to move the cursor within the input. Thus, stopping event propagation/bubbling should be used, and can solve the main issue you're asking about.

    // assuming you've grabbed an input in var input_ele
    input_ele.onkeypress = function (e) {
        e = e || window.event;
    
        if (e.stopPropagation) {
            e.stopPropagation();
        } else {
            e.cancelBubble = true;
        }
    };
    

    Using this will stop the keypress event from leaving the input element, thereby never reaching the document element to trigger the unwanted behavior. In other words, you don't break the expected behavior of a very standard control element.

提交回复
热议问题