相对于屏幕的Javascript元素位置

时间:2015-03-31 13:19:16

标签: javascript html browser position

我需要获取元素相对于屏幕或窗口左上角的位置(point(window.screenX,window.screenY)。

为什么呢?我需要桌面应用程序来绘制这个位置的东西。我能够获得整个窗口和文档的矩形,但是我无法获得窗口顶部和文档顶部之间的偏移。

如果用户已打开,例如调试浏览器的控制台,则使用window.outerHeight - window.innerHeight不起作用。

有什么想法?在SP上有一些关于它的文章,但它们都适用于我作为文档的视图端口。

编辑:其他可能的解决方案是获取文档的screenX / Y值

由于

3 个答案:

答案 0 :(得分:0)

如果您不反对使用插件,则jquery具有.position()方法,因此您可以执行doc

更新解决方案

// 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});

答案 1 :(得分:0)

您可能想要查看窗口的以下属性...

window.screen.top - 返回当前屏幕顶部的距离(以像素为单位)。 windows.screen.left - 返回从主屏幕左侧到当前屏幕左侧的距离(以像素为单位)。

答案 2 :(得分:0)

我一直在寻找相同的东西,而且令人惊讶的是,这很难实现。

有一个仅适用于Firefox的解决方案-window.mozInnerScreenXwindow.mozInnerScreenY将为您提供相对于屏幕的视口的左侧和顶部。

就我所知,对于其他浏览器,您将需要监听第一个鼠标或触摸事件。这些事件包含事件的屏幕坐标和客户端坐标,可用于计算视口的屏幕坐标。

innerScreenX = event.screenX - event.clientX;
innerScreenY = event.screenY - event.clientY;

请注意,在多显示器设置的情况下,屏幕坐标可能是意外值(例如-ve值)。

相关问题