从顶部和底部固定偏移 div

Offset fixed div from top and bottom

我的页面右侧有一个固定的 div。我将其设置为随页面滚动而不与页脚重叠,效果很好。问题是向上滚动时它与导航重叠。有没有办法让它对两者都有效?我尝试创建一个新函数

function checkOffset() {
    var a = $(document).scrollTop() + window.innerHeight;
    var b = $('#footer').offset().top;

    if (a < b) {
        $('#social-float').css('bottom', '10px');
    } else {
        $('#social-float').css('bottom', (10 + (a - b)) + 'px');
    }
}
$(document).ready(checkOffset);
$(document).scroll(checkOffset);
<nav class="nav">Nav Sample</nav>

<div id="social-float">
    <div class="sf-twitter">twitter</div>
    <div class="sf-facebook">facebook</div>
</div>

<div id="footer">footer sample</div>

Here 查看此 fiddle 以获取解决方案。 我在页面上添加了调试文本,还考虑了导航栏可能会由于顶部的其他 div 而偏移的事实。

/** 
 * This function checks for both top and bottom edges to position itself
 * on the page
 */
function checkOffset() {
    var documentTop = $(document).scrollTop();
    var currentScrollOffset = documentTop + window.innerHeight;
    var footerOffset = $('#footer').offset().top;
    var navbarEffectiveHeight = $('.nav').outerHeight() + $('.nav').offset().top;
    var $fixedElem = $('#social-float');
    var fixedElemHeight = $fixedElem.outerHeight();

  // until page scroll crosses navbar bottom edge (offset)
    if (currentScrollOffset < navbarEffectiveHeight) {
      $fixedElem.css('top', (currentScrollOffset + 10) + 'px');
        $fixedElem.css('bottom', 'unset');
    // page scroll crossed navbar bottom edge but not to extend of the height of fixed div
    // including the top and bottom spacing for it which is 20px
    } else if (currentScrollOffset < navbarEffectiveHeight + fixedElemHeight + 20) {
      $fixedElem.css('top', (window.innerHeight - (currentScrollOffset - navbarEffectiveHeight) + 10) + 'px');
        $fixedElem.css('bottom', 'unset');
    // page scroll hasn't crossed footer top edge (offset)
    } else if (currentScrollOffset < footerOffset) {
        $fixedElem.css('bottom', '10px');
        $fixedElem.css('top', 'unset');
    // page scroll crossed footer top edge (offset)
    } else {
        $fixedElem.css('bottom', (10 + (currentScrollOffset - footerOffset)) + 'px');
        $fixedElem.css('top', 'unset');
    }
}


$(document).ready(checkOffset);
$(document).scroll(checkOffset);