【原生JS】制作网页头部刷新进度条

时间:2025-03-22 15:05:25

之前的某次番啬看到油管上有这么一个进度条,当时觉得挺好玩,一直想着做一个试试,刚才弄了一下写了一个不算太好看的简陋版本,哈哈。

(本博客刷新会头部会出现,因为并没有真正的参与到浏览器加载是否完整这个渲染过程中来,所以只是一个表象,并不是说这个显示完了就浏览器也加载完了所以资源。)

效果图:

【原生JS】制作网页头部刷新进度条

先看下html:

就两个标签

        <div id="barbg">
<div id="bar">
</div>
</div>

CSS:

布局也很简单  < overflow-x > 禁止横向滚动条出现,在JS中添加个窗口事件再启用

        <style>
*{margin:;padding:;}
     body{overflow-x:hidden;}
#barbg{height:5px; background:rgb(149,143,143)}
#barbg div{width:; height:5px;
background:rgb(230,10,10);}
</style>

JS

然后原生JS的话就是这样了

        <script>
document.onreadystatechange = function(){
var bar = document.getElementById('bar');
var barbg = bar.parentNode;
var wd = document.body.scrollWidth || document.documentElement.scrollWidth;
var t = 10;
var d = 0;
var i = 0;
var timer = setInterval(goto,10);
function goto(){
d = d + t ;
bar.style.width = d + 'px';
if(d >= wd){
clearInterval(timer);
bar.style.background = 'rgba(230,10,10,0)';
none();
}
}
function none(){
var a = 10 - i;
i++;
if(a != 0 && a != 10){a = a * 0.1}
if(a === 10){a = 1}
if(a === 0){a = 0}
barbg.style.background = 'rgba(230,10,10,' + a.toFixed(1) + ')';
if(a === 0){barbg.style.display = 'none'}
if(a != 0){setTimeout(none,50);}
} } window.onresize = function(){
document.body.setAttribute('style','overflow-x: auto');
}); </script>