如何使用createEvent和dispatchEvent设置焦点并在输入文本中设置文本?

时间:2016-05-30 05:01:13

标签: javascript html javascript-events keyboard-events html.textboxfor

我试图在Javascript中编写代码,这应该将光标焦点设置在输入文本框上,并且应该触发"按键"应该设置关键的事件,比如说' A'在文本框中。

怎么做?我读过我们可以使用createEvent和dispatchEvent来实现。有什么建议吗?

1 个答案:

答案 0 :(得分:1)

试试这个

<input type="text" id="input-field" />

<script>

var addData = function(data){
var field = document.getElementById("input-field")
field.value = document.getElementById("input-field").value+data;

var keyboardEvent = document.createEvent("KeyboardEvent");
var initMethod = typeof keyboardEvent.initKeyboardEvent !== 'undefined' ?   "initKeyboardEvent" : "initKeyEvent";


keyboardEvent[initMethod](
               "keypress", // event type : keydown, keyup, keypress
                true, // bubbles
                true, // cancelable
                window, // viewArg: should be window
                false, // ctrlKeyArg
                false, // altKeyArg
                false, // shiftKeyArg
                false, // metaKeyArg
                40, // keyCodeArg : unsigned long the virtual key code, else 0
                0 // charCodeArgs : unsigned long the Unicode character associated with the depressed key, else 0
);
field.dispatchEvent(keyboardEvent);

}

 var registerEvents = function(){
 document.getElementById("input-field").addEventListener("keypress",function(event){
    alert("Key Pressed : "+ event.target.value)
 });
}();
addData("a");
addData("b");

</script>

无论如何,输入的密钥将在文本字段中可用,无需明确设置。