如何在涉及css缩放时获取页面上的点击位置

时间:2022-11-28 21:00:48

My current code is

我目前的代码是

document.addEventListener('click', function(event) {
    console.log(event.pageX + "-" + event.pageY);
});

however, there is a zoom set on the body (although I've no control over it, sometimes it's not there) and event.pageX and event.pageY are coming out wrong.

然而,身体上有一个缩放设置(虽然我无法控制它,有时它不存在),而event.pageX和event.pageY出错了。

Is there a way to get a relative value or something?

有没有办法获得相对价值或什么?

Edit:

编辑:

The css on the body is

身上的css是

body {
    zoom: 0.485417;
}

The zoom value may change (as part of some external JS - I've no control over that value, my JS doesn't set it, and it can change)

缩放值可能会改变(作为一些外部JS的一部分 - 我无法控制该值,我的JS没有设置它,它可以改变)

1 个解决方案

#1


2  

I nailed this with the help of andlrc's comment:

我在andlrc的评论的帮助下钉了这个:

var zoomLevel = getComputedStyle(document.body).zoom;
if (zoomLevel <= 0) { zoomLevel = 0.1; }
doMyThing(event.pageX / zoomLevel, event.pageY / zoomLevel);

x and y passed in to "doMyThing" is now properly positioned, regardless of what the zoom is set to.

无论缩放设置为什么,传入“doMyThing”的x和y现在都已正确定位。

#1


2  

I nailed this with the help of andlrc's comment:

我在andlrc的评论的帮助下钉了这个:

var zoomLevel = getComputedStyle(document.body).zoom;
if (zoomLevel <= 0) { zoomLevel = 0.1; }
doMyThing(event.pageX / zoomLevel, event.pageY / zoomLevel);

x and y passed in to "doMyThing" is now properly positioned, regardless of what the zoom is set to.

无论缩放设置为什么,传入“doMyThing”的x和y现在都已正确定位。