【问题标题】:How to simulate a mouse click using JavaScript?如何使用 JavaScript 模拟鼠标点击?
【发布时间】:2011-09-03 17:10:46
【问题描述】:

我知道document.form.button.click() 方法。但是,我想知道如何模拟onclick 事件。

我在 StackOverflow 上的某个地方找到了这段代码,但我不知道如何使用它:(

function contextMenuClick()
{
    var element= 'button'

    var evt = element.ownerDocument.createEvent('MouseEvents');

    evt.initMouseEvent('contextmenu', true, true,
         element.ownerDocument.defaultView, 1, 0, 0, 0, 0, false,
         false, false, false, 1, null);

    element.dispatchEvent(evt);
}

如何使用 JavaScript 触发鼠标点击事件?

【问题讨论】:

  • 你这样做的目的是什么?
  • @Nok Imchen - 你能提供一个链接到你得到代码的原始问题吗?
  • @Eric,和下面给出的链接一样
  • @jared,这里是链接stackoverflow.com/questions/433919/…

标签: javascript dom-events mouseclick-event


【解决方案1】:

(修改后的版本使其在没有prototype.js的情况下工作)

function simulate(element, eventName)
{
    var options = extend(defaultOptions, arguments[2] || {});
    var oEvent, eventType = null;

    for (var name in eventMatchers)
    {
        if (eventMatchers[name].test(eventName)) { eventType = name; break; }
    }

    if (!eventType)
        throw new SyntaxError('Only HTMLEvents and MouseEvents interfaces are supported');

    if (document.createEvent)
    {
        oEvent = document.createEvent(eventType);
        if (eventType == 'HTMLEvents')
        {
            oEvent.initEvent(eventName, options.bubbles, options.cancelable);
        }
        else
        {
            oEvent.initMouseEvent(eventName, options.bubbles, options.cancelable, document.defaultView,
            options.button, options.pointerX, options.pointerY, options.pointerX, options.pointerY,
            options.ctrlKey, options.altKey, options.shiftKey, options.metaKey, options.button, element);
        }
        element.dispatchEvent(oEvent);
    }
    else
    {
        options.clientX = options.pointerX;
        options.clientY = options.pointerY;
        var evt = document.createEventObject();
        oEvent = extend(evt, options);
        element.fireEvent('on' + eventName, oEvent);
    }
    return element;
}

function extend(destination, source) {
    for (var property in source)
      destination[property] = source[property];
    return destination;
}

var eventMatchers = {
    'HTMLEvents': /^(?:load|unload|abort|error|select|change|submit|reset|focus|blur|resize|scroll)$/,
    'MouseEvents': /^(?:click|dblclick|mouse(?:down|up|over|move|out))$/
}
var defaultOptions = {
    pointerX: 0,
    pointerY: 0,
    button: 0,
    ctrlKey: false,
    altKey: false,
    shiftKey: false,
    metaKey: false,
    bubbles: true,
    cancelable: true
}

你可以这样使用它:

simulate(document.getElementById("btn"), "click");

请注意,作为第三个参数,您可以传入“选项”。您未指定的选项取自 defaultOptions(参见脚本底部)。因此,例如,如果您想指定鼠标坐标,您可以执行以下操作:

simulate(document.getElementById("btn"), "click", { pointerX: 123, pointerY: 321 })

您可以使用类似的方法来覆盖其他默认选项。

积分应该转到kangaxHere 的原始来源(prototype.js 特定)。

【讨论】:

  • 学分应该归 kangax,如我的回答中所述。我确实让它与图书馆无关:)
  • 如何将鼠标坐标传递给这个脚本?
  • 我将编辑帖子并添加一个示例,说明如何传递鼠标坐标..
  • 我将其转换为 CoffeeScript 模块,以便在您的项目中轻松包含:github.com/joscha/eventr
  • 这与 $(el).click() 有何不同,因为您的解决方案适用于我,jquery 选项不适用
【解决方案2】:

模拟鼠标点击的更简单的more standard 方法是直接使用the event constructor 创建事件并调度它。

虽然保留MouseEvent.initMouseEvent() 方法是为了向后兼容,但应使用MouseEvent() 构造函数来创建MouseEvent 对象。

var evt = new MouseEvent("click", {
    view: window,
    bubbles: true,
    cancelable: true,
    clientX: 20,
    /* whatever properties you want to give it */
});
targetElement.dispatchEvent(evt);

演示:http://jsfiddle.net/DerekL/932wyok6/

这适用于所有现代浏览器。对于包括 IE 在内的旧浏览器,虽然 MouseEvent.initMouseEvent 已被弃用,但遗憾的是必须使用它。

var evt = document.createEvent("MouseEvents");
evt.initMouseEvent("click", canBubble, cancelable, view,
                   detail, screenX, screenY, clientX, clientY,
                   ctrlKey, altKey, shiftKey, metaKey,
                   button, relatedTarget);
targetElement.dispatchEvent(evt);

【讨论】:

  • 当我要点击的 A 元素具有 href="javascript:void(0)" 并且它响应已附加到对象的另一个点击处理程序时,这似乎失败了。跨度>
  • 有没有快速获取常见事件的方法?我注意到我可以轻松地点击按钮,但是没有标准的“mouseenter”、“mouseleave” evt 我可以引用而不是像上面那样创建一个新的 mouseevent?
  • 这些自定义属性将无法在您的事件监听器中访问。
【解决方案3】:

这是一个纯 JavaScript 函数,它将模拟目标元素上的单击(或任何鼠标事件):

function simulatedClick(target, options) {

  var event = target.ownerDocument.createEvent('MouseEvents'),
      options = options || {},
      opts = { // These are the default values, set up for un-modified left clicks
        type: 'click',
        canBubble: true,
        cancelable: true,
        view: target.ownerDocument.defaultView,
        detail: 1,
        screenX: 0, //The coordinates within the entire page
        screenY: 0,
        clientX: 0, //The coordinates within the viewport
        clientY: 0,
        ctrlKey: false,
        altKey: false,
        shiftKey: false,
        metaKey: false, //I *think* 'meta' is 'Cmd/Apple' on Mac, and 'Windows key' on Win. Not sure, though!
        button: 0, //0 = left, 1 = middle, 2 = right
        relatedTarget: null,
      };

  //Merge the options with the defaults
  for (var key in options) {
    if (options.hasOwnProperty(key)) {
      opts[key] = options[key];
    }
  }

  //Pass in the options
  event.initMouseEvent(
      opts.type,
      opts.canBubble,
      opts.cancelable,
      opts.view,
      opts.detail,
      opts.screenX,
      opts.screenY,
      opts.clientX,
      opts.clientY,
      opts.ctrlKey,
      opts.altKey,
      opts.shiftKey,
      opts.metaKey,
      opts.button,
      opts.relatedTarget
  );

  //Fire the event
  target.dispatchEvent(event);
}

这是一个工作示例:http://www.spookandpuff.com/examples/clickSimulation.html

您可以模拟点击DOM 中的任何元素。像simulatedClick(document.getElementById('yourButtonId')) 这样的东西会起作用。

您可以将对象传入options 以覆盖默认值(以模拟您想要的鼠标按钮,无论是 Shift/Alt/Ctrl 等。它接受的选项基于MouseEvents API

我已经在 Firefox、Safari 和 Chrome 中进行了测试。 Internet Explorer 可能需要特殊处理,我不确定。

【讨论】:

  • 这对我来说非常有用,在 Chrome 上,元素似乎没有 click() 事件。
  • 这很好——除了type: options.click || 'click' 应该是type: options.type || 'click'
  • 这个解决方案的问题是它不会点击包含的元素。例如。 <div id = "outer"><div id = "inner"></div></div> simulatedClick(document.getElementById('outer')); 不会点击内部元素。
  • 这不是事件冒泡的工作原理——如果你点击一个外部元素,它的 祖先 会在它冒泡时收到点击事件,但它的子元素不会。想象一下,如果您的外部 div 包含一个按钮或一个链接 - 您不希望点击外部触发对内部元素的点击。
  • 不要在这种情况下使用|| 运算符,因为哎呀,canBubble:options.canBubble || true, 现在总是评估为真,而且显然在 5 年内没人会注意到它。
【解决方案4】:

从 Mozilla 开发者网络 (MDN) 文档中,HTMLElement.click() 是您正在寻找的内容。您可以了解更多活动here

【讨论】:

  • @Ercksen 正如 MDN 页面所说,它仅在与支持它的元素(例如 类型之一)一起使用时触发元素的单击事件。
【解决方案5】:

根据 Derek 的回答,我验证了这一点

document.getElementById('testTarget')
  .dispatchEvent(new MouseEvent('click', {shiftKey: true}))

即使使用键修饰符也能按预期工作。据我所知,这不是一个已弃用的 API。你可以verify on this page as well

【讨论】:

    【解决方案6】:

    你可以使用elementFromPoint:

    document.elementFromPoint(x, y);
    

    所有浏览器都支持:https://caniuse.com/#feat=element-from-point

    【讨论】:

      【解决方案7】:

      JavaScript 代码

         //this function is used to fire click event
          function eventFire(el, etype){
            if (el.fireEvent) {
              el.fireEvent('on' + etype);
            } else {
              var evObj = document.createEvent('Events');
              evObj.initEvent(etype, true, false);
              el.dispatchEvent(evObj);
            }
          }
      
      function showPdf(){
        eventFire(document.getElementById('picToClick'), 'click');
      }
      

      HTML 代码

      <img id="picToClick" data-toggle="modal" data-target="#pdfModal" src="img/Adobe-icon.png" ng-hide="1===1">
        <button onclick="showPdf()">Click me</button>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-03-08
        • 2013-01-30
        • 2016-10-03
        • 1970-01-01
        相关资源
        最近更新 更多