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

查看:28
本文介绍了元素的屏幕坐标,通过 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.

编辑添加图片:

推荐答案

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;

确切位置取决于可见的工具栏.您可以使用 window 对象的 outer/innerWidthouter/innerHeight 属性来更接近一些.

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天全站免登陆