1. 程式人生 > >jquery div內容滾動到指定的ID位置.

jquery div內容滾動到指定的ID位置.

<html>
<head>
<script type="text/javascript" src="/jquery/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
  $(".btn1").click(function(){
    //alert($("#div").scrollTop()+" px");
    alert($("#d2").offset().top+$("#div").scrollTop()+" px");
    //alert($("#d2").offset().top - $("#div").offset().top + $("#div").scrollTop()+" px");
    $("#div").scrollTop($("#d2").offset().top - $("#div").offset().top + $("#div").scrollTop() );
  });
});
</script>
</head>
<body>
<div style="height:60px;">xxx</div>
<div id="div" style="border:1px solid black;width:200px;height:200px;overflow:auto">
This is some text.<br><div id="d1">1</div> This is some text. This is some text. This is some text. This is some text. This is some text.<div id="d2">2</div> This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text.<br><div id="d3">3</div>This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. <div id="d4">4</div>This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. <br><div id="d5">5</div>This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text.
</div>
<button class="btn1">獲得 scrollbar top offset</button>
<p>試著移動滾動條,然後再次點選按鈕。</p>
</body>
</html>