您的位置:首页 > 其它

Div 滚动条滚动到指定的位置

2014-12-19 11:23 281 查看
<!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。为精确计算结果,请在补白、边框和填充属性上使用像素单位。此方法只对可见元素有效。

详情访问:/article/1259749.html

IE8 下,亲测可用
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: