offsetTop,offsetLeft
19205 단어 left
offsetTop은 섹션이나 offsetTop 속성에 의해 지정된 부모 좌표에 대한 계산 상단 위치를 가져옵니다
offsetLeft: 섹션이나 offsetParent 속성에 의해 지정된 부모 좌표에 대한 계산의 왼쪽 위치를 가져옵니다
IE67과 FF의offsetTop 해석 결과는 다르다. FF에서는offsetParent가body이고, IE67에서는offsetParent가부급 요소이다.
즉, elem.offsetTop=elem.offsetTop+elemFather.offsetTop+elemFatherFather.offsetTop......
호환성 쓰기:
function getOffset(el){
var _t =el.offsetTop;
while(el = el.offsetParent){
_t += el.offsetTop;
}
return _t;
}
while(el = el.offsetParent)
하면, 만약, 만약...offsetParent가 존재하면 그의 offsetTop을 더해서 offsetParent가 없을 때까지 순환한다.다음은 테스트의 예입니다.
1
<!
DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"
>
2
<
html
xmlns
="http://www.w3.org/1999/xhtml"
>
3
<
head
>
4
<
meta
http-equiv
="Content-Type"
content
="text/html; charset=utf-8"
/>
5
<
title
>
offsetTop,offsetParent
</
title
>
6
<
style
type
="text/css"
>
7
*
{
margin
:
0
;
padding
:
0
;
}
8
div
{
width
:
400px
;
margin-top
:
20px
;
background-color
:
#000
;
height
:
300px
;
overflow
:
hidden
}
9
p
{
margin-top
:
30px
;
background-color
:
#F00
;
height
:
200px
;
overflow
:
hidden
}
10
a
{
display
:
block
;
margin-top
:
100px
;
background-color
:
#fff
;
height
:
20px
;
}
11
</
style
>
12
</
head
>
13
14
<
body
id
="the_body"
>
15
<
div
id
="the_div"
>
16
<
p
id
="the_p"
>
17
<
a
href
="#"
id
="the_a"
>
offsetTop
</
a
>
18
</
p
>
19
</
div
>
20
<
script
type
="text/javascript"
>
21
function
getOffset(el){
22
var
_t
=
el.offsetTop;
23
var
n
=
0
;
24
while
(el
=
el.offsetParent){
25
_t
+=
el.offsetTop;
26
n
++
;
27
alert(
'
'
+
n
+
'
offsetParent
'
)
28
}
29
return
_t;
30
}
31
alert(getOffset(document.getElementById(
'
the_a
'
)));
32
alert(document.getElementById(
'
the_a
'
).offsetTop);
//
IE67 100, offsetTop
33
</
script
>
34
35
</
body
>
36
</
html
>