window.pageYOffset和document.body.getBoundingClientRect()。top之间的区别?

时间:2018-12-27 14:47:07

标签: javascript

我正在根据进度条滚动进度条。我应该使用这两个中的哪一个?

function getScrollValue() {
    return ((parseInt(document.body.getBoundingClientRect().top) * -1));
}

function getScrollValue() {
    return window.pageYOffset;
}

2 个答案:

答案 0 :(得分:1)

除了window.pageYOffset是更专业的API以及用于检测滚动值的更高性能的解决方案之外,如果使用getBoundingClientRect().top进行相同的操作,例如身体顶部有一些可以抵消其位置的边距。

编辑

我包含了以下jsPerf Test,该内容显示了两种替代方案之间的性能存在实质性差异,以及第三种(较旧的)API对它们的不利影响。

答案 1 :(得分:0)

使用进度条标签的简单示例

gem update --system
/* test if passive events are supported */
var supportsPassive = false;
try { var opts = Object.defineProperty({}, 'passive', { get: function() { supportsPassive = true; }});
  window.addEventListener("testPassive", null, opts);
  window.removeEventListener("testPassive", null, opts);
} catch (e) {}

/* progress element */
const progress = document.querySelector('progress');

/* scroll listener */
addEventListener('scroll', e => {
    progress.value = pageYOffset/(document.body.clientHeight - innerHeight);
}, supportsPassive ? { passive: true } : false);
/* stretch and fix progress */ 
progress { width: 100%; position: fixed; }

/* add some scroll to the page */
body { margin: 0; height: 20000px; }