【问题标题】:trying to Add and remove .class to an #id after a specific pixels scrolled滚动特定像素后尝试将.class添加和删除到#id
【发布时间】:2020-06-06 03:27:53
【问题描述】:

我有一个 div,我想在用户滚动 800px 后向用户显示(基本上,固定 div 在滚动时会重叠页眉和页脚)所以我想让该 div 仅在滚动 800px 后才可见(这将通过标题横幅)并在#footer ection 之前停止 div(无法弄清楚如何在页脚之前停止该固定 div)。

如果有人能告诉如何使它仅在 800 像素滚动后可见,那就太好了。

$(window).scroll(function () {
    var $heightScrolled = $(window).scrollTop();
    var $defaultHeight = 800;

    if ( $heightScrolled < $defaultHeight )
    {
        $('#elements-main').removeClass("b")
    $('#elements-main').addClass("a")
        }
    else {
        $('#elements-main').addClass("b")
        }

});

【问题讨论】:

标签: javascript jquery css wordpress


【解决方案1】:

当不在页面的页眉和页脚区域时,此设置将显示固定的 div。我希望这会有所帮助。

(function($) {
  $(window).scroll(function() {
    const scrollPosition = $(window).scrollTop();
    const offset = 800;
    const footerOffset = $('footer').offset();
    const $fixedCard = $('#main');
    const fixedCardHeight = $fixedCard.outerHeight();
    
    if (scrollPosition > offset && scrollPosition < (footerOffset.top - fixedCardHeight)) {
      $fixedCard.attr('class', 'fixed-visible');
    } else {
      $fixedCard.attr('class', 'fixed-hidden');
    }
  });
})(jQuery);
body {
 height: 3000px;
 display: flex;
 margin: 0;
 align-items: stretch;
 justify-content: space-between;
 flex-direction: column;
}
header, footer {
 height: 800px;
 background-color: #ccc;
}
#main {
  position: fixed;
  top: 0;
  left: 0;
  height: 100px;
  width: 100%;
  background-color: #23e4c1;
}
.fixed-hidden {
 display: none;
}

.fixed-visible {
 display: fixed;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<header>Header Area</header>
<main>
<div id="main" class="fixed-hidden">Fixed Div</div>
</main>
<footer>Footer Area</footer>
</body>

【讨论】:

  • 非常感谢它正在工作,但没有页脚部分,如果我保持页脚状态它保持隐藏状态
  • 我很高兴它有帮助:)
  • 我很高兴你能帮上忙,因为我几乎尝试了 12 8 到 9 次 sn-ps 都没有成功
猜你喜欢
  • 2014-02-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多