2013-07-31 71 views
0

我有一個粘滯的邊欄繼續使用此代碼。但我只想讓它在768像素或更低的時候影響.fake-sidebar div。任何人都可以解釋如何將媒體查詢添加到我的JavaScript?將媒體查詢添加到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'); 
    } 
}); 

任何幫助表示讚賞。提前致謝!

+0

,我想利用http://modernizr.com/是最好的途徑... Modernizr的允許你很容易做到你要做的事情。 – marteljn

+0

你看過'window.matchMedia'嗎? http://www.sitepoint.com/javascript-media-queries/ –

回答

1

您可以window resize添加事件,或document ready,這取決於你想要的東西:個人

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