Jak symulować kliknięcie myszką za pomocą JavaScript?

Wiem o metodzie document.form.button.click(). Chciałbym jednak wiedzieć, jak symulować Zdarzenie onclick.

Znalazłem ten kod gdzieś tutaj na Stack Overflow, ale nie wiem jak go użyć: (

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

Jak uruchomić Zdarzenie kliknięcia myszką przy użyciu JavaScript?

Author: Peter Mortensen, 2011-05-28

6 answers

(zmodyfikowana wersja, aby działała bez prototypu.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
}

Możesz go użyć tak:

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

Zauważ, że jako trzeci parametr możesz podać w 'options'. Opcje, których nie podasz, są pobierane z opcji defaultOptions (patrz dolna część skryptu). Więc jeśli na przykład chcesz podać współrzędne myszy, możesz zrobić coś w stylu:

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

Możesz użyć podobnego podejścia, aby zastąpić inne domyślne opcje.

Napisy powinny trafić do kangax. tutaj jest oryginalne źródło (prototype.js specific).

 187
Author: TweeZz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-11-29 07:52:53

Oto czysta funkcja JavaScript, która symuluje kliknięcie (lub dowolne zdarzenie myszy) na elemencie docelowym:

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

Oto działający przykład: http://www.spookandpuff.com/examples/clickSimulation.html

Możesz symulować kliknięcie dowolnego elementu w DOM . Coś w stylu simulatedClick(document.getElementById('yourButtonId')) by zadziałało.

Możesz przekazać obiekt do options, aby nadpisać domyślne wartości (aby symulować, który przycisk myszy chcesz, czy Shift/Alt/Ctrl są przytrzymywane, itd. Opcje, które akceptuje są oparte na MOUSEEVENTS API .

Testowałem w Firefoksie, Safari i Chrome. Internet Explorer może wymagać specjalnego traktowania, nie jestem pewien.
 45
Author: Beejamin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-06-07 00:25:10

Łatwiejszym i bardziej standardowym sposobem symulacji kliknięcia myszy byłoby bezpośrednie użyciekonstruktora zdarzeń do utworzenia zdarzenia i wysłania go.

Choć MouseEvent.initMouseEvent() metoda jest zachowywana dla wstecznej kompatybilności, tworzenie obiektu MouseEvent powinno odbywać się przy użyciu MouseEvent() konstruktor.

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/

To działa na wszystkich nowoczesnych przeglądarkach. Dla starych przeglądarek, w tym IE, MouseEvent.initMouseEvent będzie musiał być używany niestety, choć jest przestarzały.

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);
 36
Author: Derek 朕會功夫,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-07-03 20:49:04

Z Dokumentacji Mozilla Developer Network (MDN) , HTMLElement.klik() tego szukasz. Możesz dowiedzieć się więcej wydarzeń Proszę..

 10
Author: Lewis,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-11-29 07:57:33

Na podstawie odpowiedzi Dereka, zweryfikowałem, że

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

Działa zgodnie z oczekiwaniami nawet z modyfikatorami klawiszy. I to nie jest przestarzałe API, o ile widzę. Możesz sprawdzić również na tej stronie .

 1
Author: Wizek,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-05-04 12:43:42

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

Kod 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>
 -1
Author: BERGUIGA Mohamed Amine,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-01-27 15:34:30