为什么document.body.scrollHeight返回不同的数字?

时间:2018-09-30 14:27:39

标签: javascript

我正在尝试获取身体的总高度,所以我正在使用 let page = document.body.scrollHeight The console is telling me that the height of my body in this scroll shot is 4728.120px。话虽如此,我正在将page登录到控制台。最初我得到4728px。然后,刷新页面后,我得到2029px。我不明白为什么这个数字会发生变化,尤其是考虑到窗口的大小尚未调整。

  let backgrounds = [
    "background_1.jpg",
    "background_2.jpg",
    "background_3.jpg",
    "background_4.jpg",
    "background_5.jpg",
    "background_6.jpg",
    "background_7.jpg",
    "background_8.jpg",
    "background_9.jpg",
    "background_10.jpg",
    "background_11.jpg",
    "background_12.jpg",
    "background_13.jpg",
    "background_14.jpg",
    "background_15.jpg",
    "background_16.jpg",
    "background_17.jpg",
    "background_18.jpg"
  ],
  i = 0;

  var page       = document.querySelector('body').scrollHeight,
      base       = backgrounds.length,
      height     = page / base,
      increment  = height;
  console.log(page);
  let points = Array(base).fill().map((_, i) => height+=increment)
  window.addEventListener('scroll', () => {
    let scroll = document.documentElement.scrollTop;
    console.log(i,points[i]);
    if (scroll >= points[i]) {
      document.body.style.backgroundImage = `url(${backgrounds[i]})`;
      i++;
    }
  });

1 个答案:

答案 0 :(得分:0)

我从您的代码中了解到,您想在用户向下滚动时更改背景(请注意,您的代码在向上滚动时不会变回背景)。

基于这个假设,我做了一个可行的演示。只需运行代码片段并滚动右下角的框即可。

const backgrounds = [
  'https://images.pexels.com/photos/1020315/pexels-photo-1020315.jpeg',
  'https://images.pexels.com/photos/255379/pexels-photo-255379.jpeg',
  'https://images.pexels.com/photos/207171/pexels-photo-207171.jpeg',
];
const mainDiv = document.getElementById('main');

const pageHeight = mainDiv.scrollHeight;
const backgroundHeight = Math.round(pageHeight / backgrounds.length);

const changePoints = backgrounds.map((value, index) => {
  const nextPoint = backgroundHeight * index;
  return nextPoint;
});
changePoints.push(pageHeight);

console.log(pageHeight, backgroundHeight, changePoints);


let currentBackgroundIndex = 0;
window.addEventListener('scroll', () => {
  const scroll = document.body.scrollTop || window.pageYOffset;
  const nextChangePoint = changePoints[currentBackgroundIndex];
  console.log(scroll, nextChangePoint);
  
  if (scroll > nextChangePoint) {
  	const currentBackground = backgrounds[currentBackgroundIndex];
    currentBackgroundIndex++;
    mainDiv.style.backgroundImage = `url(${currentBackground})`;
    console.log('Changing background',
      currentBackgroundIndex, currentBackground);
  }
});
html, body {
  padding: 0;
  margin: 0;
}

#main {
  height: 2000px;
  padding: 0;
  margin: 0;
}
<html>
<body>
  <div id="main"></div>
</body>
</html>

现在,关于您的问题,为什么scrollHeight会发生变化。我无法使用您给定的代码复制行为。我最好的猜测是,您可能正在X时刻检查它,并且主体可能仍在解析和加载元素。例如,假设您加载了两个图像,每个图像分别为50px和您的身体为100px。如果您在没有图像的情况下测量scrollHeight,则会得到100;如果在加载一张图片后,像素为150px,而在末尾则为200px。

一些避免这种情况的技术:

  1. 为所有元素增加高度。
  2. 延迟执行此代码,或在几秒钟后重新计算计算。