How to simulate a mouse click using JavaScript?

后端 未结 7 1091
无人及你
无人及你 2020-11-22 00:57

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 somew

相关标签:
7条回答
  • 2020-11-22 01:34

    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.

    0 讨论(0)
  • 2020-11-22 01:44

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

    0 讨论(0)
  • 2020-11-22 01:52

    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.

    0 讨论(0)
  • 2020-11-22 01:53

    You can use elementFromPoint:

    document.elementFromPoint(x, y);
    

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

    0 讨论(0)
  • 2020-11-22 01:58

    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);
    
    0 讨论(0)
  • 2020-11-22 01:59

    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>
    
    0 讨论(0)
提交回复
热议问题