<!doctype html>
<title>scrollTop study</title>
<style type="text/css">
.outer{
position:relative; /*为了兼容IE8,FF3.5,Chrome2,本例中如不加这一行,item2.offsetTop会以body为计算基准*/
width:100px;
height:100px;
border:15px solid #ccc;
overflow:hidden;
line-height:18px;
}
.item{
height:60px;
}
.bgColorRed{
background-Color:red;
}
.bgColorGreen{
background-Color:green;
}
</style>
<div class="outer" id="container">
container
<div class="item bgColorRed">item1</div>
<div class="item bgColorGreen" id="item2">item2</div>
</div>
<br/>
<button id="btnTest" >Test</button> <span id="result"></span>
<script type="text/javascript">
var btn = document.getElementById("btnTest");
btn.onclick = function(){
var outer = document.getElementById("container");
var item2 = document.getElementById("item2");
var result = document.getElementById("result");
outer.scrollTop ++ ;
result.innerHTML = "container.scrollTop=" + outer.scrollTop + ",item2.offsetTop=" + item2.offsetTop;
}
</script>
<title>scrollTop study</title>
<style type="text/css">
.outer{
position:relative; /*为了兼容IE8,FF3.5,Chrome2,本例中如不加这一行,item2.offsetTop会以body为计算基准*/
width:100px;
height:100px;
border:15px solid #ccc;
overflow:hidden;
line-height:18px;
}
.item{
height:60px;
}
.bgColorRed{
background-Color:red;
}
.bgColorGreen{
background-Color:green;
}
</style>
<div class="outer" id="container">
container
<div class="item bgColorRed">item1</div>
<div class="item bgColorGreen" id="item2">item2</div>
</div>
<br/>
<button id="btnTest" >Test</button> <span id="result"></span>
<script type="text/javascript">
var btn = document.getElementById("btnTest");
btn.onclick = function(){
var outer = document.getElementById("container");
var item2 = document.getElementById("item2");
var result = document.getElementById("result");
outer.scrollTop ++ ;
result.innerHTML = "container.scrollTop=" + outer.scrollTop + ",item2.offsetTop=" + item2.offsetTop;
}
</script>
代码很简单,一个100px的正方形div,border边框值为15px,overflow设置为hidden(隐藏),然后里面放了二个100*60的子div,显然60*2=120px,大于最外层容器的100px高度,所以会有一部分被截掉,为了更形象,二个子div上面还放置了一行文字,高度为18px,点击按钮后,最下面绿色子div的scrollTop递增加1(即位置不断升高,直至完全呈现出来)
为方便理解,还画了一个分析图:(值得注意的是offsetTop属性在ie8的非兼容模式下,还要加上Border的高度)