How to simulate a click by using x,y coordinates in JavaScript?

前端 未结 5 1476
闹比i
闹比i 2020-11-22 15:29

Is it possible to use given coordinates in order to simulate a click in JavaScript within a webpage?

5条回答
  •  [愿得一人]
    2020-11-22 15:58

    Yes, you can simulate a mouse click by creating an event and dispatching it:

    function click(x,y){
        var ev = document.createEvent("MouseEvent");
        var el = document.elementFromPoint(x,y);
        ev.initMouseEvent(
            "click",
            true /* bubble */, true /* cancelable */,
            window, null,
            x, y, 0, 0, /* coordinates */
            false, false, false, false, /* modifier keys */
            0 /*left*/, null
        );
        el.dispatchEvent(ev);
    }
    

    Beware of using the click method on an element -- it is widely implemented but not standard and will fail in e.g. PhantomJS. I assume jQuery's implemention of .click() does the right thing but have not confirmed.

提交回复
热议问题