您的位置:首页 > 运维架构

offsetLeft和offsetTop的定位机制

2015-08-06 16:37 323 查看
offsetLeft和offsetTop
表示相对于最近的祖先定位元素(CSS position 属性被设置为
relative
absolute
fixed
的元素)的左右偏移值

下面的例子中,初次进页面,点击第一个按钮,返回的偏移距离时相对于html文档左上角的偏移值;

第二个按钮则是相对于div,因为将他的父元素div的position属性设为了relative

第三个和第四个则都是相对于body定位

<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<style>

</style>
<script>
window.onload = function () {

};
</script>
</head>
<body>
<div id="div1">
<input id="btn1" type="button" value="父元素为默认定位的时候"/>
<br/>
<input id="btn2" type="button" value="应用父元素为relative"/>
<br/>
<input id="btn3" type="button" value="自己定位为relative"/>
<br/>
<input id="btn4" type="button" value="自己定位为absolute"/>

</div>
<script>
var oBtn1 = document.getElementById('btn1');
oBtn1.onclick = function () {
alert(this.offsetParent.tagName);
alert('offsetLeft:'+this.offsetLeft+'offsetTop:'+this.offsetTop);
};
var oBtn2 = document.getElementById('btn2');
oBtn2.onclick = function () {
document.getElementById('div1').style.position = 'relative';
this.value = "应用成功";
alert(this.offsetParent.tagName);
alert('offsetLeft:'+this.offsetLeft+'offsetTop:'+this.offsetTop);
};
var oBtn3 = document.getElementById('btn3');
oBtn3.onclick = function () {
this.style.position = "relative";
this.style.left = 20+'px';
this.style.top = 20+'px';
alert(this.offsetParent.tagName);
alert('offsetLeft:'+this.offsetLeft+'offsetTop:'+this.offsetTop);
};
var oBtn4 = document.getElementById('btn4');
oBtn4.onclick = function () {
this.style.position = "absolute";
this.style.left = 20+'px';
this.style.top = 20+'px';
alert(this.offsetParent.tagName);
alert('offsetLeft:'+this.offsetLeft+'offsetTop:'+this.offsetTop);
};
</script>

</body>
</html>


offsetParent
元素只可能是下面这几种情况:

<body>


position
不是
static
的元素

<table>
,
<th>
<td>
,但必须要
position: static


在这个例子中,页面是没有任何定位元素,于是,点击按钮后返回的就是
body
标签了。

body
元素为定位元素的终极boss,所以其上头就没有其他定位元素了。也就是说
body
元素没有
offsetParent
(尽管有时候
html
进入
offsetParent
链)。

另外,在IE和Opera浏览器下,
position: fixed
的元素没有
offsetParent
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: