JavaScript 函数仅适用于 index.html



我建立了一个有多个页面的练习网站。 主页index.html. 我编写了一个JS函数,该函数在向下滚动时更改标题的opacity。 由于某种原因,它只能在 index.html ,网站上没有其他页面。 我编写的所有其他函数都可以在所有页面上工作。 我一直在阅读以查看它是否与页面加载有关,但我真的找不到任何具体的东西。任何人都可以提供任何见解,为什么这个特定功能仅适用于index.html.

标头的 CSS

header {
  position: fixed;
  width: 100%;
  background: var(--white-background);
  border-bottom: 2px solid #f1f1f1;
  font-family: var(--company-font);
  opacity: 0;
  transition: opacity .5s;
  z-index: 10;
}

有问题的函数

即使是最后的console.log()也只是在index.html

function checkHeaderScroll() {
  if(document.location.pathname == '/index.html')  {
    if (window.pageYOffset > 10) {
      header[0].style.opacity = '1';
      logo.style.opacity = '0';
      logo.style.transform = 'translateY(-250%)';
    } else if (window.pageYOffset < 10) {
      header[0].style.opacity = '0';
      logo.style.opacity = '1';
      logo.style.transform = 'translateY(0)';
    }
  } else {
    header[1].style.opacity = '1';
  }
}
window.addEventListener('scroll', checkHeaderScroll);
console.log("hello");

这是因为checkHeaderScroll()函数中的第2行:-

if(document.location.pathname == '/index.html') {

如果您删除第 2、12、13 和 14 行,这应该适用于所有页面。

所以你的新函数看起来像:-

function checkHeaderScroll() {
    if (window.pageYOffset > 10) {
      header[0].style.opacity = '1';
      logo.style.opacity = '0';
      logo.style.transform = 'translateY(-250%)';
    } else if (window.pageYOffset < 10) {
      header[0].style.opacity = '0';
      logo.style.opacity = '1';
      logo.style.transform = 'translateY(0)';
    }
}
window.addEventListener('scroll', checkHeaderScroll);

您指出该函数仅适用于 index.html,在以下行中:if(document.location.pathname == '/index.html').因此不适用于其他页面。

最新更新