jQuery scrollTop检测需要很长时间

jQuery scrollTop detection takes very long

本文关键字:长时间 scrollTop 检测 jQuery      更新时间:2023-09-26

所以我要做的是:

我想要一个固定标题的登录页。如果用户向下滚动页面y px,我想将标题调整为x px。如果用户再次向上滚动并滚动到"线"上,它应该再次调整到原始尺寸。这是我的代码:

    $(document).scroll(function(){
        if($(document).scrollTop() > 300) {
            $("#header").animate({height: "50px"}, 400);
        }
        else {
            $("#header").animate({height: "200px"}, 400);
        }
        console.log($(document).scrollTop());
    });
        #header {
            background-color: coral;
            display: flex;
            justify-content: space-around;
            height: 200px;
            align-items: center;
            position: fixed;
            width: 100%;
            z-index: 1337;
        }
       
<html>
<body>
<div id="header">
    <a href="#">Link 1</a>
    <a href="#">Link 2</a>
    <a href="#">Link 3</a>
    <a href="#">Link 4</a>
    <a href="#">Link 5</a>
</div>
<div class="white-space">
    <h2>Some Content</h2>
</div>
    <div class="image">
        <img src="img/rsz_hnck8766.jpg">
        <div class="overlay"></div>
    </div>
<div class="white-space">
    <h2>Some Content</h2>
</div>
<div class="image">
    <img src="img/2.jpg">
    <div class="overlay"></div>
</div>
<div class="white-space">
    <h2>Some Content</h2>
</div>
</body>
<script src="includes/jquery-2.1.4.js"> </script>
</html>

现在,我的代码确实可以在向下滚动时使标题变小,当我向上滚动时也是如此,但有一个巨大的延迟。当我向上滚动并且处于scrollTop 0时,它需要几秒钟的时间才能再次调整大小。我想可能是它必须计算所有其他的scrollTop值,然后才能得到一个使标题再次变大的值。我该如何改进代码,使其能够毫不延迟地工作?

如@adeneo在评论中所述。。您可以使用另一个if语句

$(document).scroll(function(){
      if($(document).scrollTop() > 300) {
        if($("#header").height() == 200){
          $("#header").animate({height: "50px"}, 400);
        }
      }
      else {
        if($("#header").height() == 50){
          $("#header").animate({height: "200px"}, 400);
        }
      }
      console.log($(document).scrollTop());
});

工作演示