JQuery 用于调整 css 的 scrollTop 函数不起作用

JQuery scrollTop function for adjusting css not working

我正在尝试缩小滚动时的 margin-top 值,因为我使用的是滚动时消失的公告栏。

这是我目前正在使用的 CSS 的脚本,它都在 theme.liquid 文件中(我正在使用 Shopify):

<script
      src="https://code.jquery.com/jquery-3.6.0.min.js"
      integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4="
      crossorigin="anonymous"></script>
    <script>
      $(window).scroll(function(){
        if ($(this).scrollTop() > 50) {
           $('#christmas-header-image-pc').addClass('christmas-header-image-margin');
        } else {
           $('#christmas-header-image-pc').removeClass('christmas-header-image-margin');
        }
    });
</script>

      <style>
      #christmas-header-image-pc {
          top:0!important;
          margin-top:120px;
          z-index:5;
          height:auto;
          position:fixed;
        }
      .christmas-header-image-margin {
          margin-top:55px;
      }
      </style>

      <img id="christmas-header-image-pc" src="https://cdn.shopify.com/s/files/1/0568/1191/3367/files/christmas-header-decoration.svg?v=1638965731">

我似乎无法让它工作。 该值需要从 120px55px

在前端,这正在发生:

滚动时发生这种情况:

感谢任何帮助!提前致谢。

看起来你的 jQuery 工作正常,新的 class 在 scrollTop 超过 50 后被添加到图像中。

您的问题与 CSS 特异性有关,将 ID 添加到新的 class 规则集,如下所示:

#christmas-header-image-pc.christmas-header-image-margin {
  margin-top:55px;
}

这里有一个很棒的 article by MDN 关于特异性的话题。

Specificity is the means by which browsers decide which CSS property values are the most relevant to an element and, therefore, will be applied. Specificity is based on the matching rules which are composed of different sorts of CSS selectors.

jQuery(window).scroll(function(){
  if (jQuery(this).scrollTop() > 50) {
     jQuery('#christmas-header-image-pc').addClass('christmas-header-image-margin');
  } else {
     jQuery('#christmas-header-image-pc').removeClass('christmas-header-image-margin');
  }
});
section {
  min-height:2000px;
}

#christmas-header-image-pc {
    top:0!important;
    margin-top:120px;
    z-index:5;
    height:auto;
    position:fixed;
    transition:300ms;
  }
#christmas-header-image-pc.christmas-header-image-margin {
    margin-top:55px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<section>
  <img id="christmas-header-image-pc" src="https://cdn.shopify.com/s/files/1/0568/1191/3367/files/christmas-header-decoration.svg?v=1638965731">
</section>