以下是一段示例代码,可以实现在页面顶部显示一条滚动的加载条:

// 创建一个 div 元素作为加载条
const loadingBar = document.createElement('div');
loadingBar.style.width = '0%';
loadingBar.style.height = '2px';
loadingBar.style.backgroundColor = 'blue';
loadingBar.style.position = 'fixed';
loadingBar.style.top = '0';
loadingBar.style.left = '0';
loadingBar.style.zIndex = '9999';
document.body.appendChild(loadingBar);

// 监听页面滚动事件,并更新加载条的宽度
window.addEventListener('scroll', () => {
  const scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
  const scrollHeight = document.documentElement.scrollHeight || document.body.scrollHeight;
  const clientHeight = document.documentElement.clientHeight || window.innerHeight;
  const scrollPercent = (scrollTop / (scrollHeight - clientHeight)) * 100;
  loadingBar.style.width = scrollPercent + '%';
});

上面的代码中,我们首先创建了一个 div 元素作为加载条,并设置其样式和位置。然后,我们监听了页面的滚动事件,根据当前页面滚动的位置计算出页面已经滚动了多少百分比,将该百分比作为加载条的宽度,并更新加载条的样式。这样,当用户滚动页面时,就会看到一个滚动的加载条在页面顶部。

写一段js在页面顶部显示一条滚动的加载条

原文地址: https://www.cveoy.top/t/topic/4Wx 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录