2017-07-25 44 views
2

我试图让侧栏停在用户滚动后,一旦它碰到页脚。现在,我将z-index设置为-2,以便它位于页脚后面,但它稍微伸出一点点。在页脚使粘滞/固定元素停止

的JavaScript

$(document).ready(function() { 
    var floatingDiv = $('#side_bar'); 
    var floatingDivPosition = floatingDiv.position(); 
    $(window).scroll(function(){ 
     var scrollBarPosition = $(window).scrollTop(); 
     if(scrollBarPosition >= floatingDivPosition.top) { 
      floatingDiv.css({ 
       'position': 'fixed', 
       'top': 55, 
       'width': '18.6676%', 
       'z-index': -2 
      }); 
     } 
     else{ 
      floatingDiv.css({ 
       'position': 'relative', 
       'top': 0, 
       'width': '79.4392%' 
      }); 
     } 
    }); 
}); 

HTML

<div id="content"> 
    <div id="col_1"> 
    <div id="side_bar"> 
     <h4 id="cater_to">We cater to</h4> 
     <a href="#"><button class="side_bar_btns">Contractor</button></a> 
     <a href="#"><button class="side_bar_btns">Wood/Sport Floors</button></a> 
     <a href="#"><button class="side_bar_btns">Grocery/Commercial</button></a> 
     <a href="#"><button class="side_bar_btns">Education</button></a> 
     <h4 id="simplicity">Simplicity</h4> 
     <div id="all_systems_side_bar"> 
     <img src="images/all_systems_logo.png" alt="All Systems Maintenance logo. Links to more about All Systems Maintenance." width="100%"> 
     </div><!-- all systems side bar --> 
    </div><!-- side_bar --> 
    </div><!-- col_1 --> 

    <div id="col_2"> 
    //// bunch of stuff here 
    </div><!-- col_2 --> 

    <div class="clear"></div> 
</div><!-- content --> 

<footer> 
    /// bunch of stuff here 
</footer> 

CSS

#col_1 { 
    float:left; 
    margin-top:44px; 
    width:23.4994%; 
    margin-left:3.9531%;  
} 

#side_bar { 
    background:#003768; 
    min-height:665px; 
    width:79.4392%; 
    border-radius:20px; 
    box-shadow: 10px 10px 5px #888; 
} 

#col_2 { 
    float:right; 
    margin-top:44px; 
    width:68.5944%; 
    margin-right:3.9531%; 
} 

footer { 
    background-image:url(../images/foot_background.gif); 
    background-repeat:no-repeat; 
    background-size:cover; 
} 

页脚背景几乎是相同的屏幕高度(当我用Chrome浏览时大约为824px)。

+1

页脚的高度是多少? – stybl

+0

也许再加一点上下文和格式... –

+2

可以请你创建一个[mcve]吗? –

回答

0

在Youtube的https://www.youtube.com/watch?v=5s0L6dCVevk找到了这个宝石,并稍微改变它以提出以下,它的工作原理。

$(function() { 
    if ($('#side_bar').length) { 
     var el = $('#side_bar'); 
     var stickyTop = $('#side_bar').offset().top; 
     var stickyHeight = $('#side_bar').height(); 

     $(window).scroll(function(){ 
     var limit = $('footer').offset().top - stickyHeight - 20; 

     var windowTop = $(window).scrollTop(); 

     if (stickyTop < windowTop) { 
      el.css({ 
       position: 'fixed', 
       top: 55, 
       width: '18.6676%' 
      }); 
     } else { 
      el.css({ 
       position: 'static', 
       width: '79.4392%' 
      }); 
     } 

     if (limit < windowTop) { 
      var diff = limit - windowTop; 
      el.css({ 
       top: diff 
      }); 
     } 
    }); 
} 
});