<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="js/jquery.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
    var offset = $('#image2').offset(); 
    //alert(offset.top);
});
</script>
<body>
    <div id="image1" style="background-color:#0000ff;width:200px;height:100px;">
        aaa
    </div>
    
    <div id2="image2" style="background-color:#ff0000;width:200px;height:100px;margin-top:1000px;">
        bbb
    </div>
    <br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
</body>
我想知道Id为image2的div在可视范围内里顶部的距离,该怎么获取

解决方案 »

  1.   

    没明白什么意思,不过你的DOM对象ID错了<div id2="image2" style="background-color:#ff0000;width:200px;height:100px;margin-top:1000px;"><div id="image2" style="background-color:#ff0000;width:200px;height:100px;margin-top:1000px;">
      

  2.   

    $(document).ready(function() {
      var offset1 = $('#image2').offset(); 
      var offset2 = $('#image2').prev().offset();
      alert(offset1.top - offset2.top);
    });
      

  3.   

    错了,应该是$(document).ready(function() {
      var offset1 = $('#image2').offset(); 
      var offset2 = $('#image2').prev().offset();
      alert(offset1.top - offset2.top - $('#image2').prev().height());
    });
      

  4.   


    不对吧,这么算,总是1000,是可视范围内的距离,不是距离整个body顶部的距离
      

  5.   


    现在image2不在可视区域内,我想知道当滚动条滚动到可以看到image2时计算出image2距离顶部的距离(可视范围内的距离,不是距离body的距离)
      

  6.   


    可以说的详细点吗?我查看了offsetTop是偏移,没怎么懂,是相对于body的偏移吗
      

  7.   

    div 相对body的 top 距离    div.offsetTop  (可能还要考虑父容器偏移的情况)整个页面向上的偏移,即向上滚动的距离  body.scroll.offsetTop (如果拼错了 自己找正确的代码)2者 一减 就是了