如何获取元素距离页面顶部的高度

JavaScript014

如何获取元素距离页面顶部的高度,第1张

页面元素距离浏览器工作区顶端的距离  =  元素距离文档顶端偏移值  -   网页被卷起来的高度

即:

页面元素距离浏览器工作区顶端的距离 =  DOM元素对象.offsetTop -document.documentElement.scrollTop

介绍几个属性:(暂时只测了IE和firefox,实际上工作中用到的最多的是chrome)

网页被卷起来的高度/宽度(即浏览器滚动条滚动后隐藏的页面内容高度)

(javascript)        document.documentElement.scrollTop //firefox

(javascript)        document.documentElement.scrollLeft //firefox

(javascript)        document.body.scrollTop //IE

(javascript)        document.body.scrollLeft //IE

(jqurey)             $(window).scrollTop()

(jqurey)             $(window).scrollLeft()

网页工作区域的高度和宽度

(javascript)       document.documentElement.clientHeight// IE firefox    

(jqurey)             $(window).height()

元素距离文档顶端和左边的偏移值

(javascript)        DOM元素对象.offsetTop //IE firefox

(javascript)        DOM元素对象.offsetLeft //IE firefox

(jqurey)             jq对象.offset().top

(jqurey)             jq对象.offset().left

1、新建html文档。

2、书写hmtl代码<div class="box">    <!--代码开始--><div class="main"></div><div class="sub"><div class="sub01"></div><div class="sub01"></div><div class="fixed">我是固定的哟</div></div><!--代码结束--></div>。

3、书写css代码。<style type="text/css">**{padding:0pxmargin:0px}.box{width:1000px

background:#cccmargin:0 autooverflow:hidden}.main{width:770pxheight:3000px。

background:#000float:left}.sub{width:220pxbackground:#FC6float:right}.。

4、sub01{width:220pxheight:100pxbackground:#0CCmargin-bottom:10px}.fixed

{width:220pxheight:300pxbackground:#F66font:normal 13px/30px \5FAE\8F6F\96C5\

9ED1text-align:centertop:10px}</style>。

5、书写并添加js代码。<script src="js/jquery.js"></script>。这就完成了。

定义和用法

scrollTo(xpos,ypos) 方法可把内容滚动到指定的坐标。

xpos必需。要在窗口文档显示区左上角显示的文档的 x 坐标。

ypos必需。要在窗口文档显示区左上角显示的文档的 y 坐标。

滚动到顶部 为 div.scrollTo(0,0)