模拟滚动条控制内容

html代码:

<div id="div1">
    <div id="div2"></div>
</div>

<div id="div3">
    <div id="div4">
        长文本
    </div>
</div>

css代码:

 1 body,div{
 2     margin: 0;
 3     padding: 0;
 4 }
 5 #div1{
 6     width: 30px;
 7     height: 500px;
 8     background: black;
 9     position: absolute;
10     left: 10px;
11     top: 10px;
12 }
13 #div2{
14     width: 30px;
15     height: 30px;
16     background: red;
17     position: absolute;
18     left: 0;
19     top: 0;
20 }
21 #div3{
22     width: 498px;
23     height: 498px;
24     border: 1px solid green;
25     position: absolute;
26     left: 50px;
27     top: 10px;
28     overflow:hidden;
29 }
30 #div4{
31     position: absolute;
32     left: 0;
33     top: 0;
34 }

javascript代码:

window.onload = function(){
    var oDiv1 = document.getElementById("div1");
    var oDiv2 = document.getElementById("div2");
    var oDiv3 = document.getElementById("div3");
    var oDiv4 = document.getElementById("div4");
    
    iMaxTop = oDiv1.offsetHeight - oDiv2.offsetHeight;
    
    oDiv2.onmousedown = function(ev){
        var ev = ev || event;
        var disY = ev.clientY - this.offsetTop;
        
        document.onmousemove = function(ev){
            var ev = ev || event;
            var T = ev.clientY - disY;
            
            if( T < 0 ){
                T = 0;
            }else if( T > iMaxTop ){
                T = iMaxTop;
            }
            
            oDiv2.style.top = T + "px";
            
            var iScale = T / iMaxTop;
            document.title = iScale;
            
            oDiv4.style.top = (oDiv3.offsetHeight - oDiv4.offsetHeight) * iScale + "px";
        }
        
        document.onmouseup = function(){
            document.onmousemove = document.onmouseup = null;
        }
        
        return false;
    }
};

 

posted @ 2017-11-30 17:19  落叶无痕~  阅读(151)  评论(0编辑  收藏  举报