gpt4 book ai didi

javascript - 检查鼠标点击情况

转载 作者:行者123 更新时间:2023-12-01 01:33:42 24 4
gpt4 key购买 nike

此代码应该检查鼠标位置,如果鼠标单击在控制台中显示此 XY 位置,但它忽略单击事件并打印控制台鼠标坐标无需点击。

如何解决这个问题?

function getMousePos(canvas, evt) {
var rect = canvas.getBoundingClientRect();
return {
x: evt.clientX - rect.left,
y: evt.clientY - rect.top
};
}
canvas.addEventListener('mousemove', function(evt) {
var mousePos = getMousePos(canvas, evt);
canvas.addEventListener("click", check(mousePos.x,mousePos.y));
}, false);
function check(x,y){
console.log(x);
}

最佳答案

在这种情况下,最好避免嵌套 eventListener
您还可以将光标位置存储为 canvas.mouse 属性:

var canvas = document.querySelector('canvas');

canvas.addEventListener('mousemove', getMousePos);
canvas.addEventListener("click", check);

function getMousePos(evt) {
var rect = canvas.getBoundingClientRect();
canvas.mouse = {
x: evt.clientX - rect.left,
y: evt.clientY - rect.top
};
}

function check() {
console.log(canvas.mouse.x);
}
canvas {
width: 200px;
height: 200px;
background: #ddd
}
<canvas></canvas>

关于javascript - 检查鼠标点击情况,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53022861/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com