是否可以将鼠标单击调度事件()转换为< input type = text>元件? [英] Is it possible to dispatchEvent() a mouse click to a <input type=text> element?

查看:146
本文介绍了是否可以将鼠标单击调度事件()转换为< input type = text>元件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Basically I'm trying to dispatch a custom made mouse click event to a text input element using the following code (see this 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);
}

当我在 type =上运行该代码时复选框元素它完全正常,但在 type =text元素上调用它时根本不起作用。

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.

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

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

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

所以在上面的例子中 screenX,screenY,clientX clientY 将全部 0 (仍然,上述代码与复选框完全正常,无论其位置如何) 。我尝试捕获一个真实的事件,并将屏幕和客户端坐标传递给cusom制作的事件,但无济于事。

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). I tried capturing a real event and passing the screen and client coordinates to the cusom made event, to no avail.

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

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.

任何想法或者非常感谢您的见解!

Any ideas or insights would be greatly appreciated!

推荐答案

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

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/

注意:代码不兼容crossbrowser,但在ie8中失败。

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

考虑使用像jQuery这样的好的交叉浏览器库而不是原生的DOM方式 - 轮子存在且工作完美,重新发明它是浪费时间:)

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 :)

这篇关于是否可以将鼠标单击调度事件()转换为< input type = text>元件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆