js将页面上取得的元素坐标转换为电脑屏幕坐标
代码:
<!DOCTYPE html> <html> <head> <title>计算屏幕坐标</title> <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <style type="text/css"> body { margin: 0; padding: 0; } #msg { background-color: #eeeeee; height: 200px; } </style> </head> <body> <div id="msg"></div> <script type="text/javascript"> let div = document.querySelector('#msg'); let msg = ''; let firstPoint = getPoint(0, 0); window.onresize = function (e) { setTimeout(() => { firstPoint = getPoint(0, 0); showPoint(); }, 100); } window.onmousemove = function (e) { setTimeout(() => { showPoint(e); }, 100); } function showPoint(e) { msg = ''; let point; if (e) { point = getPoint(e.clientX, e.clientY); } else { point = getPoint(0, 0); } msg += '===========================================================================================<br />'; msg += '页面左上角屏幕坐标:' + firstPoint.x + ', ' + firstPoint.y + '<br />'; if (e) { msg += '事件屏幕坐标:' + e.screenX + ', ' + e.screenY + '<br />'; msg += '计算屏幕坐标:' + point.x + ', ' + point.y + '<br />'; if (e.screenX == point.x && e.screenY == point.y) { msg += '相等<br />'; } else { msg += '不相等<br />'; } } div.innerHTML = msg; } //计算屏幕坐标 function getPoint(clientX, clientY) { let left = 0; let top = 0; if (window.outerWidth + 16 == window.innerWidth && window.outerHeight + 16 == window.innerHeight) { //最大化全屏 msg += '最大化全屏状态<br />'; top = (window.outerHeight - window.innerHeight + 8) + window.screenTop + clientY; left = (window.outerWidth - window.innerWidth + 8) + window.screenLeft + clientX; } else if (window.outerWidth == window.innerWidth && window.outerHeight == window.innerHeight) { //全屏 msg += '全屏状态<br />'; top = (window.outerHeight - window.innerHeight) + window.screenTop + clientY; left = (window.outerWidth - window.innerWidth) + window.screenLeft + clientX; } else { if (window.outerWidth == screen.availWidth && window.outerHeight == screen.availHeight) { //最大化 msg += '最大化状态<br />'; top = (window.outerHeight - window.innerHeight) + window.screenTop + clientY; left = (window.outerWidth - window.innerWidth) + window.screenLeft + clientX; } else { msg += '非最大化非全屏状态<br />'; top = (window.outerHeight - window.innerHeight - 8) + window.screenTop + clientY; left = (window.outerWidth - window.innerWidth - 8) + window.screenLeft + clientX; } } return { x: left, y: top }; } </script> </body> </html>
说明:适用于谷歌浏览器,360浏览器下有BUG,因为360浏览器有状态栏。
思考:获取电脑屏幕坐标的意义是什么?