模拟滚动条

<script>
var box = my$('box');
var content = my$('content');
var scroll = my$('scroll');
var bar = my$('bar');
//1 根据内容的大小,计算滚动条的高度
// 滚动条的高度 / scroll的高度 = box的高度 / 内容的高度
// offsetHeight 元素的大小 + padding + border
// clientHeight 元素的大小 + padding
// scrollHeight 内容的大小 + padding

// 当内容的高度大于box的高度,再计算 滚动条的高度,否则的话滚动条的高度为0
var barHeight = 0;
if (content.scrollHeight > box.clientHeight) {
barHeight = box.clientHeight / content.scrollHeight * scroll.clientHeight;
}
bar.style.height = barHeight + 'px';

//2 让滚动条能够拖拽
// 2.1 当鼠标按下的时候,求鼠标在滚动条中的位置
bar.onmousedown = function (e) {
e = e || window.event;

// 鼠标在滚动条中的位置
var y = getPage(e).pageY - bar.offsetTop - box.offsetTop;
// 2.2 当鼠标在页面上移动的时候,求滚动条的位置
document.onmousemove = function (e) {
//求滚动条的位置
var barY = getPage(e).pageY - y - box.offsetTop;

// 控制bar不能移除scroll
barY = barY < 0 ? 0 : barY;
barY = barY > scroll.clientHeight - bar.clientHeight ? scroll.clientHeight - bar.clientHeight : barY;

bar.style.top = barY + 'px';

//3 当拖拽滚动条的时候,改变内容的位置

// 内容滚动的距离 / 内容最大能够滚动的距离 = 滚动条滚动的距离 / 滚动条最大能够滚动的距离

// 内容最大能够滚动的距离
var contentMax = content.scrollHeight - box.clientHeight;
// 滚动条最大能够滚动的距离
var barMax = scroll.clientHeight - bar.clientHeight;

var contentY = barY / barMax * contentMax;
content.style.top = -contentY + 'px';
}
}

document.onmouseup = function () {
// 移除鼠标移动的事件
document.onmousemove = null;
}



</script>

猜你喜欢

转载自www.cnblogs.com/pxxdbk/p/12655009.html