标签:style blog class code c color
---恢复内容开始---
jquery定位函数:offset,position,scrollTop/scrollLeft
(1)offset:获取当前元素相对于文档的偏移。只对可见元素有效。
(2) position:获取元素相对于最近的一个position为relative or absolute的元素的祖父节点的相对偏移。
(3)scrollTop()/scrollLeft()是分别获取元素滚动条距顶端的距离。
$(selector).offset()与$(selector).position()都返回包含top、left属性的对象 top/left的值为number
scrollTop() /scrollLeft()的返回值也为number类型 scroll()返回该对象本身
参考例子
测试代码:
<body height="1500px"><div style="position:relative;margin-top:1000px;height:300px;border:1px solid #0C6;"><p style="margin:50px;">compute my height</p></div></body> |
在firebug中得到的结果为:
$(‘div‘).offset() top:1000;left:8; //浏览器默认body 与视窗margin 为8px$(‘p‘).offset()top:1051;left:9; $(‘div‘).scrollTop()=0;$(‘div‘).scrollLeft()=0; |
$(‘p‘).position();<br>top:0 ;left:0; |
这个结果感觉很奇怪,第一二个结果还是意料之中,但是第三个是将滚动条拉到最下方的时算出的结果。
奇怪的事情出现了。
<body style="height:1500px;"><div style="position:relative;margin-top:1000px;height:300px;"><p style="padding:50px;">compute my height</p></div></body> |
$(‘div‘).offset() top:1000;left:8;$(‘p‘).offset()top:1000;left:8;$(‘div‘).scrollTop()=0;$(‘div‘).scrollLeft()=0; |
$(‘p‘).position();<br>top:0 ;left:0; |
|
padding不起作用了!!! 盒子模型 左至右 margin-left |border-left padding-left width padding-right|border-right margin-right
而offset()position() 读取的值是margin-left(margin-top)+border-left(border-top) padding不在其内
继续做修改:
<body style="height:1500px;"><div style="position:relative;margin-top:1000px;height:300px;border:1px solid #666;"><p style="padding:50px;">compute my height</p></div></body> |
$(‘div‘).offset()<br>top:1000;left:8;<br> $(‘p‘).offset()<br> top:1017;left:9; <br> //div>p会产生8px的margin$(‘div‘).scrollTop()=0;<br>$(‘div‘).scrollLeft()=0;<br>$(‘p‘).position();<br>top:0 ;left:0; |
****行内元素会默认1px间隔
---恢复内容结束---
jQuery的position(),offset(),scrollTop()/scrollLeft(),布布扣,bubuko.com
jQuery的position(),offset(),scrollTop()/scrollLeft()
标签:style blog class code c color
原文地址:http://www.cnblogs.com/hansu/p/3720806.html