JavaScript screenX/Y, clientX/Y和pageX/Y之间有什么区别
在本文中,我们将看到screenX/Y,clientX/Y和pageX/Y之间的区别。这些JavaScript属性的差异经常引起困惑。每个属性返回一个值,该值表示来自不同参考点的物理像素数。以下是这些属性的差异和用例:
screenX和screenY属性
screenX和screenY是只读属性,分别提供相对于全局或屏幕坐标的水平和垂直坐标。它返回一个浮点数,表示坐标。
示例: 此示例演示了在Javascript中基本使用screenX和screenY属性。
<h1 style="color: green;">
GeeksforGeeks
</h1>
<h3>The screenX and screenY property</h3>
<p>
Click on the button to open a new
window with the given parameters
and check the screenX and screenY
property.
</p>
<button onclick="getScreenXY()">
Open Window
</button>
<script>
function getScreenXY() {
// Open a new window with the
// left at 400 and the top at 200
var newWindow = window.open("", "newWindow",
"left=400, top=200, width=450, height=300");
newWindow.document.write(
"<p> This is the example window to" +
" show the usage of screenX/Y");
// Show the screenX and screenY property
newWindow.document.write(
"<br>screenX: " + newWindow.screenX
);
newWindow.document.write(
"<br>screenY: " + newWindow.screenY + "</p>"
);
}
</script>
输出:
clientX和clientY属性
clientX 和 clientY 是只读属性,分别提供内容区域内或浏览器窗口视口内的水平和垂直坐标。
例如,如果用户在网页上垂直滚动并在视口的开头点击,那么clientY将始终返回0。它返回一个双精度浮点数表示坐标。
示例: 此示例展示了在Javascript中使用 clientX 和 clientY 属性的基本用法。
<h1 style="color: green;">
GeeksforGeeks
</h1>
<h3>The clientX and clientY property</h3>
<p>
Click anywhere in this rectangle to
see the usage of the clientX and
clientY properties
</p>
<div style="width: 300px;
height: 200px;
border: 1px solid black;" onclick="showCoordinates(event)">
</div>
<p id="display"></p>
<script>
function showCoordinates(event) {
var x = event.clientX;
var y = event.clientY;
var coordinates = "clientX: " +
x + ", clientY: " + y;
document.getElementById("display")
.innerHTML = coordinates;
}
</script>
输出:
pageX 和 pageY 属性
pageX 和 pageY 是只读属性,分别返回相对于整个文档左边缘的水平和垂直坐标。也就是说,相对于浏览器窗口中完全渲染的内容区域的左边缘,并且位于 URL 地址栏的下方。 例如,如果用户向下滚动页面,它仍然会返回相对于页面顶部的坐标,而不考虑滚动量。
示例:这个示例展示了在 JavaScript 中基本使用 pageX 和 pageY 属性的方法。
<h1 style="color: green;">
GeeksforGeeks
</h1>
<h3>The pageX and pageY property</h3>
<p>
Mouse over the rectangle see the
usage of the pageX and pageY
properties
</p>
<div style="width: 300px;
height: 200px;
border: 1px solid black;"
onmousemove="showCoordinates(event)"
onmouseout="clearCoordinates()">
</div>
<p id="display"></p>
<script>
function showCoordinates(event) {
var x = event.pageX;
var y = event.pageY;
var coordinates = "pageX: " +
x + ", pageY: " + y;
document.getElementById("display")
.innerHTML = coordinates;
}
function clearCoordinates() {
document.getElementById("display")
.innerHTML = "";
}
</script>
输出: