将媒体查询添加到Javascript

时间:2013-07-31 01:28:18

标签: javascript media-queries

我有一个粘性边栏继续使用此代码。但我只希望它在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');
    }
});

感谢任何帮助。提前谢谢!

1 个答案:

答案 0 :(得分:1)

您可以在window resizedocument ready上添加活动,具体取决于您的需求:

$(window).resize(function() {
        var width = $(window).width();
        if (width < 768) {
            $('.fake-sidebar').css('position', 'relative');
        }
        else {
            $('.fake-sidebar').css('position', 'fixed');
        }
    });