dom 输入文字模拟滚动

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>无标题文档</title>
<style>
#div1{
    width:30px;
    height:500px;
    background:#000;
    position:absolute;
    left:10px;
    top:10px;
    }
#div2{
    width:30px;
    height:30px;
    position:absolute;
    background:red;
    left:0px;
    top:0px;
    }
#div3{
    width:498px;
    border:1px #ccc solid;
    height:498px;
    position:absolute;
    left:50px;
    top:10px;
    overflow:hidden;
    }
#div4{
    position:absolute;    
    }
textarea{
    position:absolute;
    left:50px;
    top:550px;
    width:500px;
    height:200px;
    }            
</style>
<script>
window.onload = function ()
{
    var odiv1 = document.getElementById('div1');
    var odiv2 = document.getElementById('div2');
    var odiv3 = document.getElementById('div3');
    var odiv4 = document.getElementById('div4');
    var otext = document.getElementsByTagName('textarea')[0];
    var ratio = odiv3.clientHeight / odiv4.offsetHeight > 1 ? 1 : odiv3.clientHeight / odiv4.offsetHeight; 
    
    function barheight()
    {
        var ratio = odiv3.clientHeight / odiv4.offsetHeight > 1 ? 1 : odiv3.clientHeight / odiv4.offsetHeight; 
        odiv2.style.height = odiv1.clientHeight * ratio + 'px';
    }
    
    barheight();
    
    otext.onkeyup = function ()
    {
        odiv4.innerHTML = otext.value;
        barheight();
    }
    
    odiv2.onmousedown = function (ev)
    {
        var ev = ev || event;
        var diy = ev.clientY - this.offsetHeight;
        if(odiv2.setCapture)
        {
            odiv2.setCapture();
        }
        document.onmousemove = function (ev)
        {
            var ev = ev || event;
            var T = ev.clientY - diy;
            var maxTop = odiv1.offsetHeight - odiv2.offsetHeight;
            
            if(T < 0 )
            {
                T = 0;
            }
            if(T > maxTop)
            {
                T = maxTop;
            }
            odiv2.style.top = T + 'px';
            odiv4.style.top = (odiv3.clientHeight - odiv4.offsetHeight)*(T/maxTop) + 'px';
            
        };
        
        document.onmouseup = function ()
        {
            document.onmousedown = document.onmousemove = null;
            if(odiv2.releaseCapture)
            {
                odiv2.releaseCapture();
            }
        }
        
        return false;
        
    }
};
</script>
</head>

<body>
    <div id="div1">
        <div id="div2"></div>
    </div>
    <div id="div3">
        <div id="div4"></div>
    </div>
    <textarea placeholder="请在文本框输入文字"></textarea>
</body>
</html>

 

posted @ 2015-01-21 23:32  mayufo  阅读(223)  评论(0编辑  收藏  举报