我知道这个问题已经问了很多次了。
我尝试了以下解决方案:
这是第五种解决方案:
var keyEvents = ['keydown', 'keyup', 'keypress'];
var noIdeaEvents = ["focus", "focusin", "mousemove", "hover", "mouseover", "mousedown", "mouseup", "click", "dblclick", "change", "mouseleave", "mouseout", "mouseenter", "blur", "focusout", "select", "pointermove", "pointerover", "pointerdown", "pointerup", "pointerout", "keydown", "keyup", "keypress", "input"];
function raiseEvents(target, eventsArr, k) {
var events = eventsArr;
for (var i = 0; i < events.length; i++) {
try {
if (window.dispatchEvent) {
if (events[i].indexOf("mouse") >= 0) {
var eventObject = document.createEvent("MouseEvents");
eventObject.initMouseEvent(events[i], true, true, window, 0, eventObject.screenX, eventObject.screenY, eventObject.clientX, eventObject.clientY, eventObject.ctrlKey, eventObject.altKey, eventObject.shiftKey, eventObject.metaKey, 0, null);
console.log(events[i] + ": initialized as MouseEvents.");
} else if (window.PointerEvent && events[i].indexOf("pointer") >= 0) {
var eventObject = document.createEvent("PointerEvent");
eventObject.initPointerEvent(events[i], true, true, window, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, null, 0, 0, 0, 0, 0, 0, 0, 0, 42, "mouse", 0, 0);
//var eventObject = new PointerEvent(events[i], { bubbles: true, cancelable: true, composed: true, pointerId: 42, pointerType: "mouse", clientX: 0, clientY: 0 });
console.log(events[i] + ": initialized as PointerEvent");
} else if (events[i].indexOf("blur") >= 0 || events[i].indexOf("focus") >= 0) {
var eventObject = document.createEvent("FocusEvent");
eventObject.initEvent(events[i], true, false);
console.log(events[i] + ": initialized as FocusEvent");
} else if (window.KeyboardEvent && events[i].indexOf("key") >= 0) {
var eventObject = document.createEvent("KeyboardEvent");
eventObject.initKeyboardEvent(events[i], true, true, window, 0, 0, 0, 0, 0, k);
console.log(events[i] + ": initialized as KeyboardEvent");
} else {
var eventObject = document.createEvent("Event");
eventObject.initEvent(events[i], true, false);
console.log(events[i] + ": initialized as Event");
}
target.dispatchEvent(eventObject);
console.log(events[i] + ": dispatch complete");
} else {
var eventObject = document.createEventObject();
console.log("EventObject is initialized (IE8)");
eventObject.button = 1;
target.fireEvent("on" + events[i], eventObject);
console.log("on" + events[i] + ": fire complete");
}
} catch (err) {
console.log(events[i] + ": " + err.message);
}
}
}
function go() {
var inputBox = document.getElementById("inputBox");
console.log(inputBox);
raiseEvents(inputBox, noIdeaEvents, 65);
}
<textarea id="inputBox"></textarea>
<button onclick="go()">Go</button>
但是,它们都无法在Chrome和Firefox浏览器中工作。
这意味着上述解决方案都无法将字符“ a”放入输入文本框。
为什么这些解决方案不起作用?
有什么技巧可以使它起作用吗?