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

Posted 王老五Plus

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了js制作列表滚动(有滚动条)相关的知识,希望对你有一定的参考价值。

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();

  直接铺上代码,简单易懂

以上是关于js制作列表滚动(有滚动条)的主要内容,如果未能解决你的问题,请参考以下文章

自动完成js - 列表的滚动条的列表向下箭头闪烁

如何制作 Bootstrap 下拉菜单的垂直滚动条

Ext Js 6.2.1 classic grid 滚动条bug解决方案

axure 制作滚动效果(不显示滚动条)

如何在 MS Word 文档中显示代码片段,因为它在 *** 中显示(滚动条和灰色背景)

如何用js监听滚动条滚动事件?