js制作列表滚动(有滚动条)

时间:2021-08-15 12:55:00
function mouseWheel(obj, fn){
var ff = navigator.userAgent.indexOf("Firefox");
if (ff != -1) {
obj.addEventListener("DOMMouseScroll", wheel, false);
}else{
obj.onmousewheel = wheel;
} function wheel(event){
var event = event || window.event;
var down = true; //判断是否向下滚动 if (event.preventDefault){ //清除默认事件
event.preventDefault();
} if (event.detail){ //FF
down = event.detail < 0;
}else{
down = event.wheelDelta > 0;
} fn.apply(obj,[event, down]); return false;
} } function scrollFn() {
var wrap = document.querySelector(".panelFather");
var middle = document.querySelector(".panelSons");
var sliderWrap = document.querySelector("#sliderWrap");
var slider = document.querySelector("#slider");
var y = 0; //设置滚动按钮高度
function scrollHeight() {
var scale =wrap.clientHeight/880;
var height = sliderWrap.offsetHeight * scale;
if (height < 50){
height = 50;
}
slider.style.height = height + "px";
}
scrollHeight(); var contMaxHeight = 880 - wrap.clientHeight;
var sliderMaxHeight = sliderWrap.offsetHeight - slider.clientHeight; //滚动函数
function move() {
if (y <= 0) { //限制滚动范围
y = 0;
}else if (y >= sliderMaxHeight) {
y = sliderMaxHeight;
} var moveScale = y / sliderMaxHeight; slider.style.top = y + "px";
middle.style.top = - contMaxHeight * moveScale + "px";
} //滚动按钮拖拽
slider.onmousedown = function (event){ var event = event || window.event;
var disY = event.clientY - slider.offsetTop; document.onmousemove = function (event){ var event = event || window.event;
y = event.clientY - disY;
move(); }
document.onmouseup = function (){
document.onmousemove = null;
}
return false;
} //自定义滚动距离
mouseWheel(wrap, function (event, down){
if (down){
y -= 40;
}else{
y += 40;
} move();
}); //键盘上下键控制上下滚动
document.onkeydown = function (event){ var event = event || window.event;
switch (event.keyCode){
case 38:
y -= 5;
break;
case 40:
y += 5;
break;
}
move();
} //点击滚动条,跳到相应位置
sliderWrap.onmousedown = function (event){ var event = event || window.event; //计算移动的距离
/*
鼠标垂直坐标 - 最外层元素上间距 = 鼠标移动的距离 y值是鼠标移动的距离再减去滚动按钮高度的一半,目的使滚动按钮高度的中心位置对准鼠标坐标
*/
y = event.clientY - wrap.offsetTop - slider.offsetHeight / 2; move();
} }
scrollFn();

  直接铺上代码,简单易懂