Javascript 元素相对于屏幕的位置

标签 javascript html browser position

我需要获取元素相对于屏幕或窗口左上角点的位置(点(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/

相关文章:

javascript - Iframe 音频在滚动时淡入淡出

javascript - Zend 将服务器 url/参数传递给 javascript 文件

html - 基于子图像高度的 DIV 高度在底部添加了一些额外的像素

javascript - 是否有任何跨浏览器兼容的方法可以将 Web URL 保存到用户桌面?

apache - 在 URL 路径中使用双斜线不好吗?

java - 如何用java代码关闭程序?

javascript - AngularJS 中的路由

javascript - 我如何将这段代码转换为javascript函数?

html - CSS 文本翻转效果?

html - Css 中的相机 View Angular 边框