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

Nok*_*hen 126 javascript javascript-events

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

我在Stack Overflow上找到了这个代码,但我不知道如何使用它:(

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);
}
Run Code Online (Sandbox Code Playgroud)

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

Twe*_*eZz 204

(修改后的版本使其无需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
}
Run Code Online (Sandbox Code Playgroud)

你可以像这样使用它:

simulate(document.getElementById("btn"), "click");
Run Code Online (Sandbox Code Playgroud)

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

simulate(document.getElementById("btn"), "click", { pointerX: 123, pointerY: 321 })
Run Code Online (Sandbox Code Playgroud)

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

积分应该去kangax.是原始来源(prototype.js具体).

  • 如我的回答所述,积分应该转到kangax.我确实让它库不可知:) (6认同)

Ben*_*ull 49

这是一个纯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);
}
Run Code Online (Sandbox Code Playgroud)

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

您可以模拟DOM中任何元素的单击.有点像simulatedClick(document.getElementById('yourButtonId'))工作.

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

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

  • 对于这样的情况,不要使用`||`运算符,因为whoops,`canBubble:options.canBubble || 是的,`现在总是评估为真,显然没有人会注意到它5年. (4认同)

Der*_*會功夫 43

模拟鼠标单击的更简单和更标准的方法是直接使用事件构造函数来创建事件并分派它.

虽然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);
Run Code Online (Sandbox Code Playgroud)

演示: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);
Run Code Online (Sandbox Code Playgroud)


Lew*_*wis 11

从Mozilla开发者网络(MDN)文档中,您正在寻找HTMLElement.click().你可以在这里找到更多活动.

  • @Ercksen正如MDN页面所说,它只在与支持它的元素一起使用时触发元素的click事件(例如<input>类型之一). (2认同)

Wiz*_*zek 6

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

document.getElementById('testTarget')
  .dispatchEvent(new MouseEvent('click', {shiftKey: true}))
Run Code Online (Sandbox Code Playgroud)

即使使用键修饰符也可以正常工作。据我所知,这不是一个过时的API。您也可以在此页面上进行验证


Gui*_* IA 6

您可以使用elementFromPoint

document.elementFromPoint(x, y);
Run Code Online (Sandbox Code Playgroud)

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