脑壳疼之滚动条案例

真绕啊

脑壳疼之滚动条案例

<script>
// 滚动条的高 / 装滚动条div的高 = box的高 / 文字div的高
// 滚动条的高 = 装滚动条div的高 * box的高 / 文字div的高

//最外面的div
var box = my$("box");
//文字div
var content = my$("content");
//装滚动条的div
var scroll = my$("scroll");
//滚动条本身
var bar = my$("bar");

//求滚动条的高
var height = scroll.offsetHeight * box.offsetHeight / content.offsetHeight;
bar.style.height = height + "px";

//给滚动条注册鼠标按下事件
bar.onmousedown = function (e) {
    //获取间距
    var spaceY = e.clientY - bar.offsetTop;
    console.log(bar.offsetTop);//滚动条到顶部的距离
    //移动
    bar.onmousemove = function (e) {
        //获取滚动条离duv的top值
        var y = e.clientY - spaceY;
        //设置最小值
        var y = y < 0 ? 0 : y;
        //设置最大值
        y = y > scroll.offsetHeight - bar.offsetHeight ? scroll.offsetHeight - bar.offsetHeight : y;
        bar.style.top = y + "px";

        //设置鼠标移动时,文字不被选中
        window.getSelection ? window.getSelection().removeAllRanges():document.selection.empty();

        //滚动的移动距离 /文字div 的移动距离 =滚动条最大的移动距离/文字div最大移动距离
        //文字div的移动距离 = 滚动的移动距离*文字div最大移动距离/滚动条最大的移动距离
        var moveY=y*(content.offsetHeight-box.offsetHeight)/(scroll.offsetHeight-bar.offsetHeight);
        content.style.marginTop=-moveY+"px";
    }
}
//鼠标抬起的时候,解绑移动事件
document.onmouseup=function () {
    bar.onmousemove=null;
}

</script>