您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

如何使用JavaScript模拟按键或点击?

如何使用JavaScript模拟按键或点击?

我的猜测是网页正在听鼠标按下而不是单击(这对可访问性不利,因为当用户使用键盘时,仅触发焦点和单击,而不是按下鼠标)。因此,您应该模拟mousedown,click和mouseup顺便说一下,这就是iPhone,iPodTouch和iPad在点击事件中所做的事情。

要模拟鼠标事件,可以将此片段用于支持DOM2Events的浏览器。对于更简单的模拟,请使用initMouseEvent代替鼠标位置。

// DOM 2 Events
var dispatchMouseEvent = function(target, var_args) {
  var e = document.createEvent("MouseEvents");
  // If you need clientX, clientY, etc., you can call
  // initMouseEvent instead of initEvent
  e.initEvent.apply(e, Array.prototype.slice.call(arguments, 1));
  target.dispatchEvent(e);
};
dispatchMouseEvent(element, 'mouSEOver', true, true);
dispatchMouseEvent(element, 'mousedown', true, true);
dispatchMouseEvent(element, 'click', true, true);
dispatchMouseEvent(element, 'mouseup', true, true);

当您触发模拟点击事件时,浏览器实际上会触发认操作(例如,导航到链接的href或提交表单)。

在IE中,等效的代码段是这样的(由于我没有IE,因此未经验证)。我认为您不能为事件处理程序提供鼠标位置。

// IE 5.5+
element.fireEvent("onmouSEOver");
element.fireEvent("onmousedown");
element.fireEvent("onclick");  // or element.click()
element.fireEvent("onmouseup");

您可以模拟keydown和keypress事件,但是不幸的是,在Chrome中,它们仅触发事件处理程序,并且不执行任何认操作。我认为这是因为DOM3事件工作草案描述了关键事件的这种时髦顺序:

这意味着您必须(在合并HTML5和DOM3事件草稿时)模拟浏览器原本会执行的大量操作。我讨厌这样做。例如,这大致是模拟输入或文本区域上的按键的方法

// DOM 3 Events
var dispatchKeyboardEvent = function(target, initKeyboradEvent_args) {
  var e = document.createEvent("KeyboardEvents");
  e.initKeyboardEvent.apply(e, Array.prototype.slice.call(arguments, 1));
  target.dispatchEvent(e);
};
var dispatchTextEvent = function(target, initTextEvent_args) {
  var e = document.createEvent("TextEvent");
  e.initTextEvent.apply(e, Array.prototype.slice.call(arguments, 1));
  target.dispatchEvent(e);
};
var dispatchSimpleEvent = function(target, type, canBubble, cancelable) {
  var e = document.createEvent("Event");
  e.initEvent.apply(e, Array.prototype.slice.call(arguments, 1));
  target.dispatchEvent(e);
};

var canceled = !dispatchKeyboardEvent(element,
    'keydown', true, true,  // type, bubbles, cancelable
    null,  // window
    'h',  // key
    0, // location: 0=standard, 1=left, 2=right, 3=numpad, 4=mobile, 5=joystick
    '');  // space-sparated Shift, Control, Alt, etc.
dispatchKeyboardEvent(
    element, 'keypress', true, true, null, 'h', 0, '');
if (!canceled) {
  if (dispatchTextEvent(element, 'textInput', true, true, null, 'h', 0)) {
    element.value += 'h';
    dispatchSimpleEvent(element, 'input', false, false);
    // not supported in Chrome yet
    // if (element.form) element.form.dispatchForminput();
    dispatchSimpleEvent(element, 'change', false, false);
    // not supported in Chrome yet
    // if (element.form) element.form.dispatchFormChange();
  }
}
dispatchKeyboardEvent(
    element, 'keyup', true, true, null, 'h', 0, '');

我认为不可能在IE中模拟关键事件。

javascript 2022/1/1 18:19:22 有483人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶