2016-09-07 142 views
2

基本上我想要我的菜單來激活固定類,當我向下滾動150像素,並且屏幕寬度大於850像素。如何保持導航欄固定在大屏幕上只使用jquery

我用這個代碼,但菜單仍然被固定在小屏幕上(小於850像素):如果需要

$(window).on('resize', function() { 
     if ($(window).width() > 850) { 
      var num = 150; 
//   $('nav#site-navigation').addClass('fixed'); 
       $(window).bind('scroll', function() { 
        if ($(window).scrollTop() > num) { 
         $('nav#site-navigation').addClass('fixed'); 
         } 
        else {      
         $('nav#site-navigation').removeClass('fixed'); 
        } 
       }); 
      } 

     else{ 
      $('nav#site-navigation').removeClass('fixed'); 
     } 

這裏我的CSS:

.fixed { 
    top: 0%; 
    width: 100%; 
    text-align: center; 
    bottom: auto !important; 
    z-index: 9999; 
    position:fixed !important; 
} 

我怎麼能只有當屏幕大於850時,纔將導航欄固定在頂部?

+0

*小屏幕*你的意思是移動設備? – spirit

+0

表示屏幕寬度不大於850像素的所有設備 – Ragmah

回答

2

您可以將媒體查詢添加到CSS類:

@media only screen and (min-width: 850px){ 
    .fixed { 
     top: 0%; 
     width: 100%; 
     text-align: center; 
     bottom: auto !important; 
     z-index: 9999; 
     position:fixed !important; 
    } 
} 
+2

,並從'javascript'代碼 – spirit

+0

@ spirit.Yes刪除'if($(window).width()> 850){'。我只是意識到我也必須這樣做。謝謝 – Ragmah

1

嘗試使用CSS @media喜歡:

@media screen and (max-width: 850px) { 
    .fixed { 
     position: static !important; 
    } 
} 
+0

基本上是的。儘管我使用了初始位置。 – Ragmah

+0

初始不工作在IE http://caniuse.com/#search=initial – Ostroffskiy

+0

將得到解決that.Thanks – Ragmah

0

我用這個基礎上@holtc理念和它的作品

@media (max-width: 850px){  
    nav#site-navigation.fixed { 
     position: initial !important; 
    }  
}