簡體   English   中英

如何使用 JavaScript 模擬鼠標點擊?

[英]How to simulate a mouse click using JavaScript?

我知道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);
}

如何使用 JavaScript 觸發鼠標單擊事件?

(修改后的版本使其無需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 })

您可以使用類似的方法來覆蓋其他默認選項。

學分應該 go 到kangax 是原始來源(特定於prototype.js)。

模擬鼠標點擊的更簡單和更標准的方法是直接使用事件構造函數來創建事件並調度它。

盡管為了向后兼容保留了MouseEvent.initMouseEvent()方法,但應該使用MouseEvent()構造函數來創建 MouseEvent object。

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

這是一個純 JavaScript function 將模擬目標元素上的單擊(或任何鼠標事件):

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'))這樣的東西會起作用。

您可以將 object 傳遞到options中以覆蓋默認值(以模擬您想要的鼠標按鈕,是否按住 Shift / Alt / Ctrl等。它接受的選項基於MouseEvents API

我在 Firefox、Safari 和 Chrome 中進行了測試。 Internet Explorer 可能需要特殊處理,我不確定。

從 Mozilla Developer Network (MDN) 文檔中, HTMLElement.click()就是您要查找的內容。 您可以在這里找到更多活動。

根據 Derek 的回答,我證實了這一點

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

即使使用鍵修飾符也可以按預期工作。 據我所知,這不是已棄用的 API。 您也可以在此頁面上進行驗證

您可以使用elementFromPoint

document.elementFromPoint(x, y);

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

不要依賴已棄用的 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);

}

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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM