简体   繁体   English

是否可以将鼠标单击调用事件()到<input type = text>元素?

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

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: 现在这是MDN上initMouseEvent()的定义:

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

So in the above example screenX, screenY, clientX and clientY would all be 0 (still, the above code works perfectly fine with checkboxes regardless of their position). 因此在上面的示例中, screenX, screenY, clientXclientY都将为0 (仍然,上面的代码与复选框完全正常,无论它们的位置如何)。 I tried capturing a real event and passing the screen and client coordinates to the cusom made event, to no avail. 我尝试捕获一个真实的事件并将屏幕和客户端坐标传递给cusom事件,但无济于事。

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! 任何想法或见解将不胜感激!

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. 注意:代码不兼容crossbrowser,但在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这样的好的crossbrowser库而不是原生的DOM方式 - 轮子存在且工作完美,重新发明它是浪费时间:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM