<!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=gb2312" />
<title>無標題文件</title>
<script type="text/javascript" src="resource/jquery-1.9.1.min.js"></script>
</head>
<script type="text/javascript">
$(function(){
// $("#container").scrollTop($("#test5").scrollHeight ()); 不行 $("#container").scrollTop($("#test4").offset().top) });
</script>
<body style="text-align:center"> <!--
var div = document.getElementById('divDetail'); div.scrollTop = div.scrollHeight; --> <div id="container" style="width:430px;height:300px;background:#00FF00;overflow:auto">
<div id="test1" style="width:400px;height:300px;background:#FFFFFF">
</div>
<div id="test2" style="width:400px;height:300px;background:#000000">
</div>
<div id="test3" style="width:400px;height:300px;background:#00FF00">
</div>
<div id="test4" style="width:400px;height:300px;background:#0000FF">
</div>
<div id="test5" style="width:400px;height:300px;background:#FFFF00">
</div>
</div>
</body>
</html>

評論例如以下:

$("#container").scrollTop($("#test4").position().top + $("#container").scrollTop())

注意position和offset方法的差別。另外#container和#test4都須要設定定位方式,比方position:relative.

兩個方法的定義。

offset():

獲取匹配元素在當前視口的相對偏移。

返回的物件包括兩個整形屬性:top 和 left。此方法僅僅對可見元素有效。

position():

獲取匹配元素相對父元素的偏移。

返回的物件包括兩個整形屬性:top 和 left。為精確計算結果,請在補白、邊框和填充屬性上使用畫素單位。此方法僅僅對可見元素有效。

詳情訪問:http://www.jb51.net/article/18340.htm

IE8 下,親測可用