Sunday, August 24, 2008

Element offset value will change in page render stage


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>offset will change in page render stage</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
</head>
<body>
<img id="image" src="http://www.google.com/logos/closing_ceremonies.gif"/>
<p>test <span id="span" style="color: blue; border: 2px solid orange; padding: 5px; background-color: yellow;">
offset will change</span> in page render stage
</p>
<script type="text/javascript" charset="utf-8">
var span = document.getElementById("span");
alert([span.offsetLeft, span.offsetTop]);
setTimeout(function(){
alert([span.offsetLeft, span.offsetTop]);
}, 1000);
</script>
</body>
</html>

比如上面的例子中,在span这个元素前还有一张图片是从服务器外部载入的,在页面渲染过程中,这个span对象会被先渲染到页面上,并有了对应的offset值,但当图片被载入页面之后,span元素又往下移了,此时offset值重新计算了,注意在opera测试中要每次清一下缓存才能看到效果。

No comments :