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

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

    it doenst work for me but it prints the correct element to the console

    this is the code:

    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);
        console.log(el); //print element to console
        el.dispatchEvent(ev);
    }
    click(400, 400);
    

提交回复
热议问题