【问题标题】:Offset fixed div from top and bottom从顶部和底部偏移固定 div
【发布时间】:2020-04-04 12:25:44
【问题描述】:

我的页面右侧有一个固定的 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>

【问题讨论】:

    标签: javascript jquery css css-position


    【解决方案1】:

    Here 查看此小提琴以获取解决方案。 我在页面上添加了调试文本,并且还考虑了导航栏可能由于顶部的其他 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);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-10-14
      • 2016-10-10
      • 1970-01-01
      • 2017-09-13
      • 2012-06-01
      • 1970-01-01
      • 2013-12-25
      相关资源
      最近更新 更多