简体   繁体   中英

How to offset top bar height dynamically when scrolling down

I am trying to offset an announcement bar when scrolling down, taking into consideration that the height of the bar is more important on smaller devices.

Here's an example of what I want to achieve : https://8kflexwarm.com/

So I ended up with this piece of code, which is working, but I feel like it is not optimized, not clean code. I figure there must be a way to offset $('.announcement-bar') instead of doing it manually with window size.

Also, why is this code not working when I refresh the screen and I'm not on top of the page ?

Is there a way to improve this code without using a library ?

 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(); }; 

Please provide a codePen, it makes it easier to help you with your question.

I came up with this untested piece of 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 || {})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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