进度条 - jQuery到Pure Vanilla JS

Joe*_*278 4 javascript jquery

我试图把这个小转换成script纯粹的vanilla JS.

普通的JS值未正确计算.

我需要什么才能计算出与jQuery版本相同的值?

请在jQuery小提琴中向下滚动以查看我的意思.

$(document).scroll(function() {
    var progressBar = $('progress'),
        docHeight = $(this).height(),
        winHeight = $(window).height(),
        max = docHeight - winHeight,
        value = $(window).scrollTop();
    progressBar.attr('max', max);
    progressBar.attr('value', value);
});
Run Code Online (Sandbox Code Playgroud)

演示jQuery

在下面,我的纯JS不起作用:

var progressBar = function() {
    var myBar = document.querySelector('progress'),
        docHeight = document.clientHeight,
        winHeight = window.clientHeight,
        max = docHeight - winHeight,
        value = window.scrollY;
    myBar.setAttribute('data-max', myBar.getAttribute('max'));
    myBar.setAttribute('max', max);
    myBar.setAttribute('data-value', myBar.getAttribute('value'));
    myBar.setAttribute('value', value);
};
document.addEventListener('scroll', progressBar);
window.addEventListener('resize', progressBar);
Run Code Online (Sandbox Code Playgroud)

我在香草的尝试

谢谢!!

Mic*_*haw 5

您需要使用不同的属性来访问文档和窗口高度.

  1. document.clientHeight应该是document.body.clientHeight.该clientHeight属性旨在返回HTML元素的计算高度.使用该body元素符合该设计.

  2. window.clientHeight应该是window.innerHeight.由于window它不是HTML元素,因此它具有自己的高度属性.

我还简化了进度条属性设置逻辑.除非您有一些外部要求来设置data-maxdata-value属性,否则您可以删除这些行.如果确实需要设置这些属性,则可以使用该dataset属性.

var progressBar = function() {
    var myBar = document.querySelector('progress'),
        docHeight = document.body.clientHeight,
        winHeight = window.innerHeight,
        max = docHeight - winHeight,
        value = window.scrollY;
    myBar.setAttribute('max', max);
    myBar.setAttribute('value', value);
};
document.addEventListener('scroll', progressBar);
window.addEventListener('resize', progressBar);
Run Code Online (Sandbox Code Playgroud)

见JSFiddle.