日期:2014-05-16  浏览次数:20398 次

jquery 如何获取div在可视范围内离顶部的距离
<!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在可视范围内里顶部的距离,该怎么获取

------解决方案--------------------
offsetTop
------解决方案--------------------
没明白什么意思,不过你的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;">
------解决方案--------------------
错了,应该是

$(document).ready(function() {
var offset1 = $('#image2').offset(); 
var offset2 = $('#image2').prev().offset();
alert(offset1.top - offset2.top - $('#image2').prev().height());
});
------解决方案--------------------
div 相对body的 top 距离 div.offsetTop (可能还要考虑父容器偏移的情况)

整个页面向上的偏移,即向上滚动的距离 body.scroll.offsetTop (如果拼错了 自己找正确的代码)

2者 一减 就是了