我在IE,Chrome,FireFox上尝试了下一个代码,它不起作用;
我想模拟输入框中的字符。
为什么它不按预期工作?
你能帮忙吗?
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Example XHTML page</title>
<script>
function simulateKeyPress1() {
var txt1 = document.getElementById("txt1");
if (document.implementation.hasFeature("KeyboardEvents", "3.0"))
{
var event = document.createEvent("KeyboardEvent");
//initialize the event object
event.initKeyboardEvent('keydown', true, false, null, 0,
false, 0, false, 77, 0);
txt1.dispatchEvent(event);
}
}
function simulateKeyPress2() {
//for Firefox only
var txt1 = document.getElementById("txt1");
//create event object
var event = document.createEvent("KeyEvents");
//initialize the event object
event.initKeyEvent("keydown", true, true, document.defaultView,
false, false,true, false, 65, 65);
//fire the event
txt1.dispatchEvent(event);
}
</script>
</head>
<body>
<input id="txt1" type="text"/>
<p><button onclick="simulateKeyPress1()">SomeButton</button></p>
</body>
</html>