頁面頂部捲軸效果
<!DOCTYPE html>
*{padding: 0;margin: 0;}
body{height:1000px;}
。barTop{height: 4px;width: 0%;position: fixed;top: 0;left: 0;right: 0;}
class TopBarScroll{
vH = document。body。scrollHeight; //頁面整個頁面高度
cH = document。documentElement。clientHeight; //視窗可視高度
constructor(color){
this。color = color || ‘#3498db’;
}
el = null;
createDiv(){
this。el = document。createElement(‘div’);
this。el。className=“barTop”
this。el。style。backgroundColor = this。color;
document。body。appendChild(this。el);
}
init(){
let fag = this。hasScrollbar();
if(fag){
this。createDiv();
window。onscroll = this。scroll。bind(this);
}
}
scroll(){ //window 滾動事件
let sH = this。getScrollTop();
let s = this。getPercent(sH,(this。vH - this。cH))
this。el。style。width = s;
}
getScrollTop(){ //捲軸距上距離
var scrollTop=0;
if(document。documentElement&&document。documentElement。scrollTop)
{
scrollTop=document。documentElement。scrollTop;
}
else if(document。body)
{
scrollTop=document。body。scrollTop;
}
return scrollTop;
}
getPercent(num, total){ //獲取百分比
num = parseFloat(num);
total = parseFloat(total);
if (isNaN(num) || isNaN(total)) {
return “-”;
}
return total <= 0 ? “0%” : (Math。round(num / total * 10000) / 100。00)+“%”;
}
hasScrollbar() { //判斷是否有捲軸,如果沒有就不生成DIV元素
return document。body。scrollHeight > (window。innerHeight || document。documentElement。clientHeight);
}
}
window。onload = function(){
let b = new TopBarScroll(“#9b59b6”);
b。init();
}