Javascript 是否可以将鼠标单击 dispatchEvent() 发送到 <input type=text> 元素?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5352709/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 16:48:20  来源:igfitidea点击:

Is it possible to dispatchEvent() a mouse click to a <input type=text> element?

javascriptmouseeventdispatchevent

提问by Philip Kamenarsky

Basically I'm trying to dispatch a custom made mouse click event to a text input element using the following code (see this jsFiddle):

基本上,我正在尝试使用以下代码将自定义鼠标单击事件分派到文本输入元素(请参阅此jsFiddle):

function simulateClick(id) {
    var clickEvent = document.createEvent("MouseEvents");
    clickEvent.initMouseEvent("click", true, true, window, 1, 0, 0, 0, 0,
        false, false, false, false, 0, null);

    var element = document.getElementById(id);
    element.dispatchEvent(clickEvent);
}

When I run that code on a type="checkbox"element it works perfectly fine but it doesn't work at all when called on a type="text"element.

当我在一个type="checkbox"元素上运行该代码时,它工作得很好,但在type="text"元素上调用时它根本不起作用。

Now here's the definition of initMouseEvent()on MDN:

现在这里是initMouseEvent()MDN上的定义:

event.initMouseEvent(type, canBubble, cancelable, view, 
                 detail, screenX, screenY, clientX, clientY, 
                 ctrlKey, altKey, shiftKey, metaKey, 
                 button, relatedTarget);

So in the above example screenX, screenY, clientXand clientYwould all be 0(still, the above code works perfectly fine with checkboxes regardless of their position). I tried capturing a real event and passing the screen and client coordinates to the cusom made event, to no avail.

所以在上面的例子中screenX, screenY, clientXclientY并且都是0(仍然,上面的代码在复选框上工作得很好,不管它们的位置如何)。我尝试捕获一个真实事件并将屏幕和客户端坐标传递给自定义事件,但无济于事。

I though maybe text input elements ignore custom mouse events due to security reasons, but then element.focus()should't work either, which it does.

我虽然由于安全原因,文本输入元素可能会忽略自定义鼠标事件,但element.focus()也不应该工作,它确实如此。

Any ideas or insights would be greatly appreciated!

任何想法或见解将不胜感激!

采纳答案by Martin Jespersen

As far as i can tell your code works fine. However it does not focus the input field as you may think, but the event is fired on the input field just fine, as seen in this fiddle: http://jsfiddle.net/ENvZY/

据我所知,您的代码工作正常。但是,它并没有像您想象的那样聚焦输入字段,但是在输入字段上触发事件就好了,如这个小提琴所示:http: //jsfiddle.net/ENvZY/

Note: the code is not crossbrowser compatible though, it fails in ie8.

注意:虽然代码不是跨浏览器兼容的,但它在 ie8 中失败。

Consider using a good crossbrowser library like jQuery instead of going the native DOM way - the wheel exists and works perfectly, reinventing it is a waste of time :)

考虑使用像 jQuery 这样好的跨浏览器库,而不是采用原生 DOM 方式 - 轮子存在并且运行良好,重新发明它是浪费时间:)