screenX / Y,clientX / Y和pageX / Y有什么区别?

JavaScript

宝儿AA

2020-03-12

screenX/ YclientX/ YpageX/有Y什么区别

另外,对于iPad Safari,计算结果是否与台式机类似?还是因为视口而有所不同?

如果您能指出一个例子,那就太好了。

第979篇《screenX / Y,clientX / Y和pageX / Y有什么区别?》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

4个回答
十三蛋蛋 2020.03.12

两者之间的差异将在很大程度上取决于您当前所指的浏览器。每个属性都以不同的方式或根本没有实现这些属性。Quirksmode提供了很多有关W3C标准(例如DOM和JavaScript事件)的浏览器差异的文档。

逆天TomHarry 2020.03.12
  1. pageX / Y<html>以CSS像素为单位给出相对于元素的坐标
  2. clientX / Y给出相对于viewportCSS像素的坐标
  3. screenX / Y给出相对于screen设备内像素的坐标

关于您的最后一个问题,在台式机和移动浏览器上计算是否相似...为了更好地理解-在移动浏览器上,我们需要区分两个新概念:布局视口可视视口视觉视口是页面上当前显示在屏幕上的部分。布局视口是在桌面浏览器上呈现的整个页面(包括所有在当前视口中不可见的元素)的同义词。

在移动浏览器中,pageXpageY仍然相对于页面以CSS像素为单位,因此您可以获得相对于文档页面的鼠标坐标。另一方面clientXclientY定义与视觉视口有关的鼠标坐标

这里还有另一个关于视觉视口和布局视口之间差异的stackoverflow线程:视觉视口和布局视口之间的差异?

另一个很好的资源:http : //www.quirksmode.org/mobile/viewports2.html

斯丁斯丁 2020.03.12

在JavaScript中:

pageXpageYscreenXscreenYclientX,和clientY返回一个数,其指示物理“CSS像素”的数量的点是从参考点。事件点是用户单击的位置,参考点是左上角的点。这些属性返回到该参考点的水平和垂直距离。

pageX and pageY:
Relative to the top left of the fully rendered content area in the browser. This reference point is below the URL bar and back button in the upper left. This point could be anywhere in the browser window and can actually change location if there are embedded scrollable pages embedded within pages and the user moves a scrollbar.

screenX and screenY:
Relative to the top left of the physical screen/monitor, this reference point only moves if you increase or decrease the number of monitors or the monitor resolution.

clientX and clientY:
Relative to the upper left edge of the content area (the viewport) of the browser window. This point does not move even if the user moves a scrollbar from within the browser.

For a visual on which browsers support which properties:

http://www.quirksmode.org/dom/w3c_cssom.html#t03

w3schools has an online Javascript interpreter and editor so you can see what each does

http://www.w3schools.com/jsref/tryit.asp?filename=try_dom_event_clientxy

<!DOCTYPE html>
<html>
<head>
<script>
function show_coords(event)
{
  var x=event.clientX;
  var y=event.clientY;
  alert("X coords: " + x + ", Y coords: " + y);
}
</script>
</head>

<body>

<p onmousedown="show_coords(event)">Click this paragraph, 
and an alert box will alert the x and y coordinates 
of the mouse pointer.</p>

</body>
</html>

LEYEvaL 2020.03.12

这是一张解释之间的差异pageYclientY

pageY vs clientY

pageX和和clientX分别相同


pageX/Y 坐标相对于整个渲染页面的左上角(包括通过滚动隐藏的部分),

clientX/Y坐标是相对于页面可见部分(通过浏览器窗口“可见”)的左上角。

观看演示

您可能永远都不需要 screenX/Y

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android