How to simulate a mouse click using JavaScript?

后端 未结 7 1284
无人及你
无人及你 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: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);
    

提交回复
热议问题