在实际应用或许会需要计算出指定div距离窗口或则它的父元素的顶部的距离。
下面通过实例对此做一下简单的介绍,代码实例如下:
<!DOCTYPE html> <html> <head> <meta charset=" utf-8"> <meta name="author" content="http://www.gaodaima.com/" /> <title>搞代码</title> <style type="text/css"> *{ margin:0px; padding:0px; } #box{ width:200px; height:200px; background-color:blue; top:100px; left:100px; padding:50px; position:absolute; } #inner{ width:100px; height:100px; background-color:red; } span{color:red;} </style> <script type="text/javascript" src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function(){ $("#bt").click(function(){ $("#first").text($("#inner").offset().top); $("#second").text($("#inner").position().top); $("#third").text($("#inner").offset().top-$("body").scrollTop()); }) }) </script> </head> <body style="height:1000px;"> <div id="box"> <div id="inner"></div> </div> <div style="margin-top:420px;"> 距离文档顶部距离:<span id="first"></span> 距离父元素顶部的距离:<span id="second"></span> 距离窗口顶部的距离:<span id="third"></span> </div> <input type="button" id="bt" value="点击显示结果"> </body> </html>