这里是 javascript 的新手,我在浏览时使用游戏手柄(使用游戏手柄 API 和 TamperMonkey)搞砸了,并且在模拟单击屏幕上的某个(x,y)坐标时遇到了麻烦。它报告“无法读取null的属性'dispatchEvent'”,即使我在click函数中控制台记录我的元素,它也会返回null。任何人都可以帮助澄清可能存在错误的地方吗?
(function() {
'use strict';
const rAF = window.mozRequestAnimationFrame || window.requestAnimationFrame;
window.addEventListener("gamepadconnected", (event) => {
console.log("A gamepad connected:");
console.log(event.gamepad);
});
window.addEventListener("gamepaddisconnected", (event) => {
console.log("A gamepad disconnected:");
console.log(event.gamepad);
});
window.addEventListener('gamepadconnected',function(e) {
updateLoop();
})
function updateLoop() {
if(navigator.getGamepads) {
var gp = navigator.getGamepads()[0];
}
const xboxButtonB = gp.buttons[1];
const xboxButtonA = gp.buttons[0];
if (xboxButtonA.pressed) {
console.log('a pressed');
click(1200,500);
}
if (xboxButtonB.pressed) {
console.log('b pressed')
click(700,500);
}
setTimeout(function () {
rAF(updateLoop);
}, 150);
}
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);
}
})();