无法更改滚动条值

Can't change scrollbar values

我编写了一个简单的代码来更改滚动条的值以及 document.scrollTop 但我无法让它工作。

var scroll = document.scrollTop; 
var container = document.getElementById('test');
container.innerHTML = scroll;

 var pb = document.getElementById('progress-bar');
 pb.value = 2;
 var change = function()
 {   pb.value = 2;
     pb.value++;
 };

 if (scroll > 0){
     change();
 };

谁能告诉我哪里做错了?

问题:

您没有在 post 中分享很多细节,但是根据您 post 的内容,我们可以注意到您当前的代码存在一些问题:

  • 如评论中所述,您需要使用 document.body.scrollTop 因为 document.scrollTopundefined 因为附有卷轴 记录 body 而不是 document 本身。
  • 使用您的实际代码,您不会更改进度条值,因为 change() 函数未附加到任何事件,它只是在文档加载时调用。

解法:

如果想在页面滚动时改变进度条值,需要在bodyonscroll事件中进行。

演示:

我制作了一个示例演示来向您展示它应该如何工作,以及当我们在视图中滚动时进度条如何变化:

document.body.onscroll = function() {
  var pb = document.getElementById('progress-bar');
  var fullHeight = document.body.scrollHeight;
  var value = 100 - (document.body.scrollTop / fullHeight) * 100;
  pb.value = value;
};
#progress-bar {
  margin-top: 200px;
}
<div style="width:250px; height:1400px">
  <progress id="progress-bar" value="100" max="100"></progress>
</div>

以上函数附加到 document.bodyonscroll 事件,每当滚动主体时,它都会计算滚动高度 (document.body.scrollTop) 与完整可滚动高度的比较(document.body.scrollHeight) 并将此值放在进度条中。