1. 程式人生 > >jq自定義滾動條

jq自定義滾動條

//滾動條
		$(function () {
			//文字高度
			var contentH = $('.content').height();
			//可視高度
			var viewH = $('.talent-theory-border').height();
			//滾動條高度
			var scrollH = $('.scrollbar').height();
			//滑塊高度
			var sliderH = viewH/contentH*scrollH;
			var sliderDistence = 0;
			$('.scrollbar p').css('height', sliderH+'px' );
			// 滾動事件
			$('.talent-theory-border').on('scroll',function() {
				//文字滾動距離
				var scrollTop = $('.talent-theory-border').scrollTop();
				//滑塊滾動距離
				sliderDistence = scrollTop/(contentH-viewH)*(scrollH-sliderH);
				// console.log(scrollTop)
				$('.scrollbar p').css('top', sliderDistence+'px' );
			});

			//點選事件
			$('.scrollbar').click(function(event) {
				// console.log(sliderDistence);
				var move = 20;
				if (event.offsetY > sliderDistence + sliderH) {
					$('.scrollbar p').css('top', sliderDistence+move+'px' );
					sliderDistence = sliderDistence + move;
				} else if( event.offsetY < sliderDistence){
					$('.scrollbar p').css('top', sliderDistence-move+'px' );
					sliderDistence = sliderDistence - move;
				}
				$('.talent-theory-border').scrollTop(sliderDistence/(scrollH-sliderH)*(contentH-viewH))
			});
			// 拖拽
			// var drag = false;
			$('.scrollbar p').mousedown(function(e) {
				// drag = true;
				var startY = e.offsetY;
				console.log(startY);

				$(document).mousemove(function(e) {
					// if (drag) {
						var moveY = e.offsetY;
						var dValue = moveY-startY;
						var mouseH = sliderDistence+dValue;
						if ( mouseH <= 0) {
							mouseH = 0;
						} else if (mouseH >= scrollH - sliderH){
							mouseH = scrollH - sliderH;
						}
						$('.scrollbar p').css('top', mouseH+'px' );
						$('.talent-theory-border').scrollTop(mouseH/(scrollH-sliderH)*(contentH-viewH));
					// }
				});
				$(document).mouseup(function(e){ 
					// drag = false;
					$(document).off('mousemove');
					$(document).off('mouseup');
				});
				return false;
			});
		})