In: Javascript| Web前台相关| 英语
31 Jul 2009According to this document at Mozilla Developer Center, Javascript 1.5 has been implemented in a browser since at least the first releases of Mozilla as open source browser, which means, in other words, since around 1998. Let’s assume it was 2002 which is marked as the release of the 1.0 version.
And I was doing some [...]
在一些应用中,可能会有需要知道某一个控件在页面中的位置,在网上比较容易找到下面这个解决方法。
在页面中有一个按钮:
<input id="a" type="button" value="click me to get position"
onclick="getPos(this)" />
在脚本中响应点击事件的是这个函数:
1
2
3
4
5
6
7
8
9
function getPos(e){
var t=e.offsetTop;
var l=e.offsetLeft;
while(e=e.offsetParent){
t+=e.offsetTop;
l+=e.offsetLeft;
}
alert("top="+t+"\nleft="+l);
}
这个方法的实现相当精炼,意思就是先取得自己的相对位置,再叠加其最近的相对位置容器(offsetParent,它不一定是其父节点)的相对位置,直至顶层位置容器(一般就是body),从而得出该节点的相对位置。
不过,很快就发现这个函数也许并不够用,因为我在页面里有可能使用了一些CSS来使得本来平铺的画面变成一个滚动区域,例如设置了父节点的height为 某个值,并且其overflow设为auto或者scroll。这时,上面的方法因为没有计算其滚动偏移,所以所得的值不一定是元素当前的绝对位置,所以 我对上面的方法进行了一些小改动,实际上就是加入了对其滚动偏移量的计算。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
function getPosition(sender) {
[...]
by Stephen Swoyer
30 September 2008
Who’s ahead: Microsoft Corp.’s .NET or Sun Microsystems Inc.’s Java Platform Enterprise Edition (Java EE)?
Five years in and counting, the battle still rages with no clear victor. However, according to a new survey, .NET appears to be widening its lead over Java EE, [...]
姓名:郑玏
性别:男
职业:程序员
爱好:KTV、乒乓球、台球、五子棋、围棋、编程
语言:中文、英语、闽南语
Email: