How to fire keyboard events in Javascript?

前端 未结 1 1453
粉色の甜心
粉色の甜心 2021-01-29 03:51

I\'m giving a value to a textbox and then giving focus to it.

document.getElementById(\'textbox\').value=\"abcd\";
document.getElementById(\'textbox         


        
相关标签:
1条回答
  • 2021-01-29 04:17

    You can't trigger browser keypress behavior with JavaScript simulated keypresses. You can only trigger your own function. What that means if that if you add a keypress event listener that checks if the a key is pressed and then does something, you can trigger that behavior, but you can't for example make the browser pull up it's "find" bar when you trigger ctrl+F. That would be a security issue.

    The appropriate way would be to write your own function for selecting and fire it whenever you need it.

    This should do what you're looking for: Live demo (click).

    <input type="text" id="my-input" value="Some text.">
    

    JavaScript:

    var myInput = document.getElementById('my-input');
    
    myInput.addEventListener('click', function() {
      this.focus();
      this.select();
    });
    
    var event = new Event('click');
    myInput.dispatchEvent(event);
    
    0 讨论(0)
提交回复
热议问题