获取元素相对于浏览器的绝对位置 [英] Getting absolute position of an element relative to browser

查看:1420
本文介绍了获取元素相对于浏览器的绝对位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个div设置为css类float,float为:

I have a div set to the css class float with float being:

.float {
display:block; 
position:fixed; 
top: 20px;
left: 0px;
z-index: 1999999999;
}
* html .float {position:absolute;}

导致元素保持在页面上的固定位置(* html部分是使它在IE中工作)。我使用javascript来水平和垂直移动元素的位置。

This class causes the element to stay in a fixed position on the page (the *html part is to make it work in IE). I am using javascript to shift the position of the element horizontally and vertically.

我需要得到相对于浏览器窗口的div在JavaScript中的绝对位置像素从浏览器窗口的顶部和左边div是)。现在,我使用以下:

I need to get the absolute position of the div relative to the browser window in javascript (how many pixels from the top and left of the browser window the div is). Right now, I am using the following:

pos_left = document.getElementById('container').offsetLeft;
pos_top = document.getElementById('container').offsetTop;

上面的代码适用于IE,Chrome和FF,但在Opera中它返回0。我需要一个适用于所有这些浏览器的解决方案。任何想法?

The code above works for IE, Chrome, and FF, but in Opera it returns 0 for both. I need a solution that works for all of those browsers. Any ideas?

Btw:保持跟踪javascript的更改是可能的,但这不是我寻找的解决方案,由于性能原因。

Btw: Keeping tracking of the changes made by javascript is possible, but that is not the solution I am looking for due to performance reasons. Also, I am not using jquery.

推荐答案

如果可以使用项目样式元素;

If you can use items style element;

<div id="container" style="top: 20px;left: 0px;z-index: 1999999999;">

您可以使用元素样式属性获取它;

You can get it with element style attribute;

var top = parseInt(document.getElementById('container').style.top.split('px')[0], 10); // This row returns 20

您可以使用顶部,左,宽,高等。 ..

这篇关于获取元素相对于浏览器的绝对位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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