javascript位置関係(一)---offsetなどのテスト
3557 ワード
offsetParent :
( ): DOM :
, body
ie7 , body,
html
ie7 , layout,
offsetParent layout
( ): DOM :
, offsetParent
offsetLeft/Top : ( ),
offsetParent 。
1:
offsetParent -> body
offsetLeft -> html
2:
2-1:ie7 :
2-1-1: , offsetLeft/Top body
2-1-2: ,
2-2: :
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>size</title>
<link rel="stylesheet" href="">
<style type="text/css">
* {
margin: 0px;
padding: 0px;
}
#parent {
width: 200px;
height: 200px;
margin: 0 auto;
margin: 50px;
border: 1px solid green;
position: relative;
padding: 20px;
}
#son {
width: 100px;
height: 100px;
border: 1px solid yellow;
margin: 50px;
padding: 10px;
/* position: absolute;
left: 0px;
top: 5px; */
}
/*
1: ,offsetTop (margin)+ (border)+ ( margin)101px
offsetLeft offsetTop IE8 , :
1、>IE8 offsetLeft offsetTop offsetParent , IE8 BODY ;
2、I>E8 offsetLeft offsetTop offsetParent borderLeftWidth borderTopWidth ,IE8 ;
2: , top/left+
margin+padding ie8/chrome : top top/left+ mg+ pad
ie8 : margin( )
*/
</style>
</head>
<body>
<div id="parent">
<div id="son">
son
</div>
</div>
<script type="text/javascript">
window.onload = function() {
var p = document.getElementById("parent");
var s = document.getElementById("son");
alert(s.offsetTop + "px"+"----"+getOffsetTop(s));
function getOffsetLeft(o) {
var left = 0;
while (o != null && o != document.body) {
left += o.offsetLeft;
o = o.offsetParent;
}
return left;
}
/*
* ie6 ff offsetTop
*/
function getOffsetTop(o) {
var top = 0;
while (o != null && o != document.body) {
top += o.offsetTop;
o = o.offsetParent;
}
return top;
}
}
</script>
</body>
</html>