0

我有一个与此代码有关的粘性侧边栏。但我只希望它在 768px 或以下时影响 .fake-sidebar div。谁能解释如何向我的 javascript 添加媒体查询?

var sticky_offset;
$(document).ready(function() {
    var original_position_offset = $('.fake-sidebar').offset();
    sticky_offset = original_position_offset.top;
    $('.fake-sidebar').css('position', 'fixed');
});

$(window).scroll(function () {
    var sticky_height = $('.fake-sidebar').outerHeight();
    var where_scroll = $(window).scrollTop();
    var window_height = $(window).height();     

    if((where_scroll + window_height) > sticky_offset) {
        $('.fake-sidebar').css('position', 'relative');
    }

    if((where_scroll + window_height) < (sticky_offset + sticky_height))  {
        $('.fake-sidebar').css('position', 'fixed');
    }
});

任何帮助表示赞赏。提前致谢!

4

1 回答 1

1

您可以根据需要添加事件 onwindow resize或 on document ready

$(window).resize(function() {
        var width = $(window).width();
        if (width < 768) {
            $('.fake-sidebar').css('position', 'relative');
        }
        else {
            $('.fake-sidebar').css('position', 'fixed');
        }
    });
于 2013-07-31T15:39:15.317 回答