导航栏应该只在我滚动时显示,但当我刷新页面时已经可见,然后在滚动时消失

The navigation bar should only show when I scroll, but is already visible when I refresh the page, then disappears when scrolling

我正在创建一个页面,导航栏只应在滚动几千像素后出现。但是当我刷新浏览器时,导航栏首先出现并在我开始滚动时消失。之后一切正常。

如何在页面刷新时隐藏该栏?

这里是我用过的JS代码:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

    <script type="text/javascript">
      $(document).ready(function(){$(window).scroll(function(){
            if( $(this).scrollTop() > 4000){
              $('#navigation').fadeIn( "slow", "linear" )
            } else {
              $('#navigation').fadeOut( "slow", "linear" )
            }
          })
        })
     </script>

这里是我用过的 CSS 代码:

nav ul {
        position:fixed;
        list-style: none;
        width: 1100px;
        height: 40px;
        margin: 30px 222px auto;
        padding: 20px 20px 20px 20px;
        background-color: #798c39;
        text-align: center;
        }

这取决于导航栏的 space 是否在加载时为其保留。

我怀疑它是给你显示的 JS,在这种情况下你需要确保它的不透明度:加载时为 0。

对代码的唯一改动是在样式表中添加:

nav {
  opacity: 0;
}

这是假设 fadeIn/fadeOut 关键帧只是改变不透明度。如果他们也改变了一些维度,例如,那也需要迎合。也许您可以向我们展示那些关键帧以便我们检查?

也许尝试另一种方式。我建议使用纯粹的 javascript 和 css,而不是用 jquery 做所有事情。这种方法效率更高,效果更好。

const nav = document.querySelector('#navigation');

function showNav(){
    nav.classList.add('show');
}

function hidewNav(){
    nav.classList.remove('show');
}
var currPos = window.scrollY;
document.addEventListener('scroll', () => {
  if (window.scrollY < currPos) {
  //scroll up
    hidewNav();
  } else {
  //scroll down
    showNav();
  }
  currPos = window.scrollY;
});
body {
  margin: 0;
  height: 2000px;
  margin-top: 100px;
}

nav {
  position: fixed;
  list-style: none;
  width: 100%;
  height: 70px;
  top: 0;
  margin: 0;
  background-color: #798c39;
  text-align: center;
  transform: translateY(-100px);
  transition: 0.3s;
}

.show {
  transform: translateY(0);
}
<html>
  <head>

  </head>
  <body>
    <header>
      <nav id="navigation">
        <ul>

        </ul>
      </nav>
    </header>
    <main>
   
    </main>
  </body>
</html>