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

前端 未结 5 1477
闹比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:32

    This is just torazaburo's answer, updated to use a MouseEvent object.

    function click(x, y)
    {
        var ev = new MouseEvent('click', {
            'view': window,
            'bubbles': true,
            'cancelable': true,
            'screenX': x,
            'screenY': y
        });
    
        var el = document.elementFromPoint(x, y);
    
        el.dispatchEvent(ev);
    }
    

提交回复
热议问题