在做項目時我們通常要根據需求制作相關的滾動條,如何制作屬于自己的精美滾動條呢?
下面是一個小例子,可以通過js封裝,直接調用就可以了
滑塊div
function srolldiv(wrapDiv,contentDiv,sliderWrap,sliders){
//設定比例
//clientHeight - 不包括border
var scale = wrapDiv.clientHeight / contentDiv.clientHeight;
//設定滑塊的高度
var h1 = sliderWrap.clientHeight * scale;
//為了合理設定高度,設定滑塊的最小高度
if (h1 < 50){
h1 = 50;
}else if (scale >= 1){
//說明目前内容能過完全顯示在可視區域内,不需要滾動條
sliderWrap.style.display = "none";
}
//設定滑塊的高度
//slider.style.height = h1 +"px";
//設定y軸的增量
var y = 0;
//為wrap添加滾輪事件
wrapDiv.onmousewheel = function(e){
var event1 = event || e
if (event.wheelDelta < 0){
//滑動條向下滾動
y += 10;
}else if (event.wheelDelta > 0){
//滑動條向上滾動
y -= 10;
}
var moveSlider=y+sliders.clientHeight;//滾動條移動高度 移動的距離+滑塊高度
//y變化時說明在滾動,此時使滾動條發生滾動,以及設定content内容部分滾動
//判斷極端情況,滑塊不能劃出螢幕
if (y <= 0){
//滑塊最多滑到頂部
y = 0;
moveSlider=0;
}
if(y >= sliderWrap.clientHeight - sliders.clientHeight){
//滑塊最多滑到最底部
y = sliderWrap.clientHeight - sliders.clientHeight;
moveSlider=y+sliders.clientHeight;//滾動條移動高度 移動的距離+滑塊高度
}
//更新滑塊的位置
sliders.style.top = y +"px";
var proportionSlider=moveSlider/sliderWrap.clientHeight;//移動高度與滾動條高度的比例
var totalHeight=contentDiv.clientHeight-sliderWrap.clientHeight;//需要滾動的大div與滾動條的高度差,大div需要滾動的總高度
var rollingHeight=proportionSlider*totalHeight;//大div滾動的高度 高度差*比例
//更新輪播内容的位置
contentDiv.style.top = -rollingHeight +"px";
}
var isDrop = false; //移動狀态的判斷滑鼠按下才能移動
var divY;
//滑鼠拖動
wrapDiv.onmousedown = function(e){
var e = e || window.event; //要用event這個對象來擷取滑鼠的位置
divY = e.clientY - sliders.offsetTop;
isDrop = true; //設為true表示可以移動
}
//滑鼠移動時
wrapDiv.onmousemove = function(e){
//是否為可移動狀态
if(isDrop){
var e = e || window.event;
var moveY = e.clientY - divY; //得到距離上邊距離
var moveSlider=moveY+sliders.clientHeight;//滾動條移動高度 移動的距離+滑塊高度
//範圍限定 當移動的距離最小時取最大 移動的距離最大時取最小
//範圍限定一
if(moveY <= 0){
moveY = 0;
moveSlider=0;
}else if(moveY>=sliderWrap.clientHeight - sliders.clientHeight){
//滑塊最多滑到最底部
moveY = sliderWrap.clientHeight - sliders.clientHeight;
moveSlider=y+sliders.clientHeight;//滾動條移動高度 移動的距離+滑塊高度
}
//更新滑塊的位置
sliders.style.top = moveY + "px";
var proportionSlider=moveSlider/sliderWrap.clientHeight;//移動高度與滾動條高度的比例
var totalHeight=contentDiv.clientHeight-sliderWrap.clientHeight;//需要滾動的大div與滾動條的高度差,大div需要滾動的總高度
var rollingHeight=proportionSlider*totalHeight;//大div滾動的高度 高度差*比例
//更新輪播内容的位置
contentDiv.style.top = -rollingHeight +"px";
y=moveY;//記錄top距離,滑鼠移動時友善擷取
}else{
return;
}
}
//滑鼠放開
wrapDiv.onmouseup = function(){
isDrop = false; //設定為false不可移動
}
}