固定元素重叠成页脚

时间:2016-10-24 12:39:54

标签: jquery html css

我试图阻止滚动元素重叠到网站上的页脚。我已经知道它在某个元素的页面顶部没有重叠但它仍然在页脚上重叠。

以下是我目前的代码:

// fix the orange box to the top after scrolling a certain amount
$(window).scroll(function() {
    // get the scroll position top
    var window_pos = $(window).scrollTop();

    // fix the element on scroll
    if (window_pos >= $('#sticky').offset().top) {
        $('#suggestions').attr('style', 'position: fixed; top: 0px;');


        // prevent overlapping into the footer
        if (window_pos >= $('#sticky2').offset().top || window_pos >= $('.footer').offset().top) {
            alert("exceeded");
            $('#suggestions').attr('style', 'position: absolute');
        } else {
            // restore fixed position
            if ($(document).scrollTop() + window.innerHeight < $('#sticky2').offset().top) {
                $('#suggestions').attr('style', 'position: fixed; top: 0px;');
            }
        }
    } else if (window_pos < $('#sticky').offset().top - 20) {
        $('#suggestions').attr('style', 'position: absolute');
    }
});

并且两个div元素如下:

<div id="sticky" style="height: 20px; margin-top: 5px; visibility: hidden;"></div>
<div id="sticky2" style="height: 50px; margin-top: 10px; visibility: hidden;"></div>

任何帮助将不胜感激。

谢谢!

1 个答案:

答案 0 :(得分:0)

试试这个

$(window).scroll(function() {
    // get the scroll position top
    var window_pos = $(window).scrollTop();

    // fix the element on scroll
    if (window_pos >= $('#sticky').offset().top) {
        $('#suggestions').css({
            'position': 'fixed',
            'top': '0px'
        });


        // prevent overlapping into the footer
        if (window_pos >= $('#sticky2').offset().top || window_pos >= $('.footer').offset().top) {

            $('#suggestions').css({
                'position': 'static',
                'top': 'auto'
            });
        } else {
            // restore fixed position
            if ($(document).scrollTop() + window.innerHeight < $('#sticky2').offset().top) {
                $('#suggestions').css({
                    'position': 'fixed',
                    'top': '0px'
                });
            }
        }
    } else if (window_pos < $('#sticky').offset().top - 20) {
        $('#suggestions').css({
            'position': 'static',
            'top': 'auto'
        });
    }
});