繁体   English   中英

如何在向下滚动时动态偏移顶部条形高度

[英]How to offset top bar height dynamically when scrolling down

我试图在向下滚动时偏移公告栏,考虑到条形的高度在较小的设备上更重要。

这是我想要实现的一个例子: https//8kflexwarm.com/

所以我最终得到了这段代码,这是有效的,但我觉得它没有优化,不是干净的代码。 我认为必须有一种方法来抵消$('.announcement-bar')而不是手动使用窗口大小。

另外,为什么当我刷新屏幕并且我不在页面顶部时,此代码无法正常工作?

有没有办法在不使用库的情况下改进此代码?

 if($(window).width() >= 686){ var a = $(".site-header").offset().top; function scrollListener(){ if($(document).scrollTop() > a) { $('.site-header').css({"margin-top":"-40px"}); $('.site-header').css({"transition":"0.4s"}); } else { $('.site-header').css({"margin-top":"0px"}); $('.site-header').css({"transition":"0.4s"}); } }; $(document).scroll(scrollListener); scrollListener(); } else if($(window).width() >= 370) { var a = $(".site-header").offset().top; function scrollListener(){ if($(document).scrollTop() > a) { $('.site-header').css({"margin-top":"-65px"}); $('.site-header').css({"transition":"0.4s"}); } else { $('.site-header').css({"margin-top":"0px"}); $('.site-header').css({"transition":"0.4s"}); } }; $(document).scroll(scrollListener); scrollListener(); } else { var a = $(".site-header").offset().top; function scrollListener(){ if($(document).scrollTop() > a) { $('.site-header').css({"margin-top":"-90px"}); $('.site-header').css({"transition":"0.4s"}); } else { $('.site-header').css({"margin-top":"0px"}); $('.site-header').css({"transition":"0.4s"}); } }; $(document).scroll(scrollListener); scrollListener(); }; 

请提供codePen,它可以更轻松地帮助您解决问题。

我想出了这个未经测试的javascript:

var myApp = (function(app) {

  const $elements = {
    siteHeader = null,
  }

  function setPosition() {
    const scrollTop = $(document).scrollTop()
    const offsetTop = $elements.siteHeader.offset().top

    if(scrollTop > offsetTop){
      $elements.siteHeader.css({'margin-top':`${$elements.siteHeader.height() * -1}px`})
    } else {
      $elements.siteHeader.css({'margin-top':'0px'})
    }
  }

  function initialize() {
    // Wait for all elements to be created
    $(function() {
      $elements.siteHeader = $('.site-header')
      setPosition()
      $(document).scroll(setPosition)
      $(document).resize(setPosition)
    })
  }

  initialize()

  return app;
})(myApp || {})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM