Changing the keypress

后端 未结 6 1156
北荒
北荒 2020-11-27 06:16

In an input box or contenteditable=true div, how can I modify a keypress for the letter \"a\" to return a keybress for the letter \"b\"? I.e., every time you type the letter

6条回答
  •  庸人自扰
    2020-11-27 06:56

    Here a simple example to replace , to . using Vanilla JavaScript

    // change ',' to '.'
    document.getElementById('only_float').addEventListener('keypress', function(e){
        if (e.key === ','){
            // get old value
            var start = e.target.selectionStart;
            var end = e.target.selectionEnd;
            var oldValue = e.target.value;
    
            // replace point and change input value
            var newValue = oldValue.slice(0, start) + '.' + oldValue.slice(end)
            e.target.value = newValue;
    
            // replace cursor
            e.target.selectionStart = e.target.selectionEnd = start + 1;
    
            e.preventDefault();
        }
    })

提交回复
热议问题