如何使用 JavaScript 模拟鼠标点击?

发布于 2024-11-10 07:54:22 字数 509 浏览 4 评论 0原文

我知道 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 触发鼠标单击事件?

I know about the document.form.button.click() method. However, I'd like to know how to simulate the onclick event.

I found this code somewhere here on Stack Overflow, but I don't know how to use it :(

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);
}

How do I fire a mouse click event using JavaScript?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

挽手叙旧 2024-11-17 07:54:22

(修改版本使其无需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
}

document.getElementById("btn").addEventListener("click", function(e)
{
  console.log("clicked", e.screenX, e.screenY);
});

simulate(document.getElementById("btn"), "click");
simulate(document.getElementById("btn"), "click", { pointerX: 123, pointerY: 321 });
<button id="btn">Click me</button>

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

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

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

积分应转至 kangax这里是原始来源(特定于 prototype.js) 。

(Modified version to make it work without 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
}

document.getElementById("btn").addEventListener("click", function(e)
{
  console.log("clicked", e.screenX, e.screenY);
});

simulate(document.getElementById("btn"), "click");
simulate(document.getElementById("btn"), "click", { pointerX: 123, pointerY: 321 });
<button id="btn">Click me</button>

Note that as a third parameter you can pass in 'options'. The options you don't specify are taken from the defaultOptions (see bottom of the script). So if you for example want to specify mouse coordinates you can do something like:

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

You can use a similar approach to override other default options.

Credits should go to kangax. Here's the original source (prototype.js specific).

策马西风 2024-11-17 07:54:22

模拟鼠标点击的一种更简单且更标准的方法是直接使用事件构造函数用于创建事件并分派它。

虽然MouseEvent.initMouseEvent() 方法保留了向后兼容性,应使用 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);

An easier and more standard way to simulate a mouse click would be directly using the event constructor to create an event and dispatch it.

Though the MouseEvent.initMouseEvent() method is kept for backward compatibility, creating of a MouseEvent object should be done using the MouseEvent() constructor.

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

Demo: http://jsfiddle.net/DerekL/932wyok6/

This works on all modern browsers. For old browsers including IE, MouseEvent.initMouseEvent will have to be used unfortunately though it's deprecated.

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);
与往事干杯 2024-11-17 07:54:22

这是一个纯 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 中进行了测试,可能需要特殊处理,我不确定。

Here's a pure JavaScript function which will simulate a click (or any mouse event) on a target element:

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);
}

Here's a working example: http://www.spookandpuff.com/examples/clickSimulation.html

You can simulate a click on any element in the DOM. Something like simulatedClick(document.getElementById('yourButtonId')) would work.

You can pass in an object into options to override the defaults (to simulate which mouse button you want, whether Shift/Alt/Ctrl are held, etc. The options it accepts are based on the MouseEvents API.

I've tested in Firefox, Safari and Chrome. Internet Explorer might need special treatment, I'm not sure.

眼眸 2024-11-17 07:54:22

根据德里克的回答,我验证了

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

即使使用键修饰符也能按预期工作。据我所知,这并不是一个已弃用的 API。您也可以在此页面上进行验证

Based on Derek's answer, I verified that

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

works as expected even with key modifiers. And this is not a deprecated API, as far as I can see. You can verify on this page as well.

神妖 2024-11-17 07:54:22

来自 Mozilla 开发者网络 (MDN) 文档,HTMLElement。 click() 就是您要寻找的。您可以在此处了解更多活动。

From the Mozilla Developer Network (MDN) documentation, HTMLElement.click() is what you're looking for. You can find out more events here.

[浮城] 2024-11-17 07:54:22

您可以使用 elementFromPoint

document.elementFromPoint(x, y);

所有浏览器都支持:< a href="https://caniuse.com/#feat=element-from-point" rel="noreferrer">https://caniuse.com/#feat=element-from-point

You can use elementFromPoint:

document.elementFromPoint(x, y);

supported in all browsers: https://caniuse.com/#feat=element-from-point

手心的温暖 2024-11-17 07:54:22

不要依赖已弃用的 API 功能。所有浏览器都支持下面的示例。 在此处查看文档和示例

if (document.createEvent) {

    // Create a synthetic click MouseEvent
    let event = new MouseEvent("click", {
     bubbles: true,
     cancelable: true,
     view: window
    });

    // Dispatch the event.
    link.dispatchEvent(event);

}

Don't rely on deprecated API features. All browsers support the example below. See docs and example here

if (document.createEvent) {

    // Create a synthetic click MouseEvent
    let event = new MouseEvent("click", {
     bubbles: true,
     cancelable: true,
     view: window
    });

    // Dispatch the event.
    link.dispatchEvent(event);

}
面如桃花 2024-11-17 07:54:22

在复杂的下拉菜单中“其他一切都失败”的情况下,这对我有用,希望它对其他人有帮助:

// Dispatch mousedown, then mouseup to simulate a full click,
// using absolute x/y coordinates..
function simulateMouseClick(element) {
    const rect = element.getBoundingClientRect();
    const x = rect.left;
    const y = rect.top;
    let targetWindow = window;
    if (typeof unsafeWindow !== 'undefined') {
        targetWindow = unsafeWindow
    }
    let targetElement = document.elementFromPoint(x, y);
    if (!targetElement) {
        targetElement = element;
    }
    targetElement.dispatchEvent(new MouseEvent('mousedown', {
        view: targetWindow,
        bubbles: true,
        cancelable: true,
        clientX: x,
        clientY: y
    }));
    targetElement.dispatchEvent(new MouseEvent('mouseup', {
        view: targetWindow,
        bubbles: true,
        cancelable: true,
        clientX: x,
        clientY: y
    }));
    targetElement.dispatchEvent(new MouseEvent('click', {
        view: targetWindow,
        bubbles: true,
        cancelable: true,
        clientX: x,
        clientY: y
    }));
}

用法:

simulateMouseClick(document.getElementById("btn"));

This worked for me in a situation where "everything else failed" in a complex dropdown menu , hope it helps someone else:

// Dispatch mousedown, then mouseup to simulate a full click,
// using absolute x/y coordinates..
function simulateMouseClick(element) {
    const rect = element.getBoundingClientRect();
    const x = rect.left;
    const y = rect.top;
    let targetWindow = window;
    if (typeof unsafeWindow !== 'undefined') {
        targetWindow = unsafeWindow
    }
    let targetElement = document.elementFromPoint(x, y);
    if (!targetElement) {
        targetElement = element;
    }
    targetElement.dispatchEvent(new MouseEvent('mousedown', {
        view: targetWindow,
        bubbles: true,
        cancelable: true,
        clientX: x,
        clientY: y
    }));
    targetElement.dispatchEvent(new MouseEvent('mouseup', {
        view: targetWindow,
        bubbles: true,
        cancelable: true,
        clientX: x,
        clientY: y
    }));
    targetElement.dispatchEvent(new MouseEvent('click', {
        view: targetWindow,
        bubbles: true,
        cancelable: true,
        clientX: x,
        clientY: y
    }));
}

usage:

simulateMouseClick(document.getElementById("btn"));
节枝 2024-11-17 07:54:22

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>

JavaScript Code

   //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 Code

<img id="picToClick" data-toggle="modal" data-target="#pdfModal" src="img/Adobe-icon.png" ng-hide="1===1">
  <button onclick="showPdf()">Click me</button>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文