一个元素的屏幕坐标,通过Javascript [英] Screen Coordinates of a element, via Javascript

查看:69
本文介绍了一个元素的屏幕坐标,通过Javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在浏览器窗口中获取元素的屏幕坐标(即相对于屏幕的左上角)。获取窗口的大小和位置(screenX,screenY)很容易(使用jQuery)可以获得元素的偏移量($('element')。offset()。left)。

I'm trying to get the screen coordinates (that is, relative to the top left corner of the screen) of an element in a browser window. It's easy to get the size and position of the window (screenX, screenY) and it's easy (with jQuery) to get the offset of the element ($('element').offset().left).

但是,我需要知道从元素到屏幕角落的像素数。我发现一些似乎是特定于IE的东西,但我希望这可以在尽可能多的浏览器中工作。

However, I need to know how many pixels it is from the element all the way to the corner of the screen. I've found some things that appear to be specific to IE, but I'd like this to work in as many browsers as possible.

编辑添加图片:
alt text http://img72.imageshack.us/img72/7938/offsetugh.jpg

推荐答案

window.screenX / Y 不支持IE。但是对于其他浏览器来说,近似的位置是:

window.screenX/Y are not supported on IE. But for other browsers, a close approximation of position is:

var top = $("#myelement").offset().top + window.screenY;
var left = $("#myelement").offset().left + window.screenX;

确切位置取决于可见的工具栏。您可以使用窗口 outer / innerWidth outer / innerHeight 属性c $ c>对象近似近一点。

Exact position depends on what toolbars are visible. You can use the outer/innerWidth and outer/innerHeight properties of the window object to approximate a little closer.

IE不提供太多的窗口属性,但奇怪的是,一个点击事件对象将为您提供与屏幕位置的点击。所以我想你可以有一个校准页面,要求用户点击红点并用

IE doesn't provide much in the way of window properties, but oddly enough, a click event object will provide you with the screen location of the click. So I suppose you could have a calibration page which asks the user to "click the red dot" and handle the event with

function calibrate(event){
    var top = event.screenY;
    var left = event.screenX;
}

或者可能使用 mouseenter / leave 事件使用该事件的坐标进行校准。虽然您无法确定鼠标从左侧,右侧,顶部或底部是否输入。

Or possibly use the mouseenter/leave events using the coordinates of that event to calibrate. Though you'd have trouble determining if the mouse entered from the left, right, top, or bottom.

当然,只要移动屏幕,您将会需要重新校准。

Of course, as soon as they move the screen you'll need to recalibrate.

有关浏览器属性兼容性的更多信息,请参阅 PPK的对象模型表

For lots more on browser property compatibilities see PPK's Object Model tables.

这篇关于一个元素的屏幕坐标,通过Javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆