繁体   English   中英

滚动上方的Div时固定标题

[英]Fixed Header when the Div above is scrolled past

我有此设置,以便在页面滚动400px时#headermenu变得固定。 但是,根据屏幕尺寸,该区域上方的div高度将有所变化。

当上面的div的底部(#mixedheightheader)到达窗口顶部时,我需要JS使#headermenu变得固定。

JSFIDDLE

预先感谢您的帮助

<div id="mixedheightheader"></div>

 $(function() {    $('#headermenu'); }); $(window).scroll(function() {    if ($(document).scrollTop() < 400)     {        if ($('#headermenu'))         {            $('#headermenu');            $('#headermenu').stop().css({ top: '0', position: 'relative' });        }    }    else     {        if ($('#headermenu'))         {            $('#headermenu');            $('#headermenu').stop().css({ top: '0', position: 'fixed' });        }      } }); 
 body { height: 3000px } #headermenu { width: 100%; background: black; min-height: 100px; } #mixedheightheader { top: 0; bottom: 0; width: 100%; height: 100vh; min-height: 200px; overflow: hidden; background: grey; clear: both; } #below { width: 100%; background: darkgrey; height: 100px; position: relative; z-index: -1; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="mixedheightheader"></div> <div id="headermenu"></div> <div id="below"></div> 

我已经更新了你的小提琴:

https://jsfiddle.net/yLon2oj3/11/

$(function() {    
  var isFixed = false; //This is to not fix if already fixed and reverse

    $(window).scroll(function() {
    var mixedHeightHeader = $('#mixedheightheader');
    //This uses the offset top position and the height to calculate the bottom of your variable header
    var mixedHeightHeaderBottom = mixedHeightHeader.offset().top + mixedHeightHeader.height();
    var headerMenu = $('#headermenu');


    if ($(document).scrollTop() < mixedHeightHeaderBottom && isFixed)       {        
        if (headerMenu) {                  
        headerMenu.css({
            top: '0',
            position: 'relative'
        });  
        isFixed = false;
        //this is to remove the placeholder space of the fixed top nav, when its not fixed to top
        mixedHeightHeader.css('margin-bottom', '0');
      }    
    }    
    else  if ($(document).scrollTop() > mixedHeightHeaderBottom && !isFixed)   {        
      if (headerMenu) {                      
        headerMenu.css({
          top: '0',
          position: 'fixed'
        });
        //This holds the position that was occupied by the fixed top nav when it was a relative element, because its now taken out of the flow.
        mixedHeightHeader.css('margin-bottom', headerMenu.height() + 'px');
      }
      isFixed = true;
    }
    });

});

暂无
暂无

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

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