我需要获取元素相对于屏幕或窗口左上角点的位置(点(window.screenX,window.screenY)。
为什么?我需要桌面应用程序在这个位置上画一些东西。我能够获得整个窗口和文档的矩形,但无法获得窗口顶部和文档顶部之间的偏移量。如果用户打开了浏览器的调试控制台,则使用 window.outerHeight - window.innerHeight
不起作用。
有什么想法吗? SP 上有一些关于它的文章,但相对于文档的 View 端口,所有这些文章都对我有用。
编辑:其他可能的解决方案是获取文档的 screenX/Y 值
谢谢
最佳答案
如果你不反对使用插件,jquery 有 .position() 方法,这样你就可以为文档做
已更新解决方案
// get element position relative to the document
var pos = $("#element").position();
var elePosX = pos.left;
var elePosY = pos.top;
// get window position relative to screen
var winPosX = window.screenX;
var winPosY = window.screenY;
// calculate the height of the navigation/toolbar
var navHeight = window.outerHeight - window.innerHeight;
// absolute x relative to the screens top left is the
//windows x position + the elements x position
var absX = winPosX + elePosX;
// absolute y relative to the screens top left is the
// windows y position + the height of the nav bar + the
// elements y position
var absY = winPosY + navHeight + elePosY;
// output values
console.log({"x": absX, "y": absY});
关于Javascript 元素相对于屏幕的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29369696/