2015-07-20 29 views
0

我嘗試使用可摺疊標題製作自適應網站。標題必須在文檔寬度超過992px時摺疊,並且必須僅在寬度小於992時固定。使可摺疊標題正確自適應

問題是:當我們調整窗口大小時,崩潰的能力不會像預期的那樣消失。但是,當我們從小到大的窗口寬度調整大小時,它就可以工作。

我用簡單的jQuery代碼:

$(function() { 

    var width = $(document).width(); 

    $(window).on("orientationchange load resize", function() { 
     width = $(document).width(); 
     if (width > 992) { 
      $(window).scroll(function() { 
       var header = $('header'); 

       if ($(this).scrollTop() > 50) { 

        header.addClass('collapse'); 

       } else { 

        header.removeClass('collapse'); 
       } 
      }); 
     } 
    }); 

請看小提琴:http://jsfiddle.net/19fmc8wa/2/

感謝。

回答

1

在這裏,你幾乎擁有它。如果我關閉了功能,請告訴我,但我儘量保持與您的原始代碼類似。

$(function(){ 

    function collapse(subj, removalBool){ 
     if (subj && !removalBool){ 
      $(subj).removeClass('collapse'); 
     } 
     else { 
      $(subj).addClass('collapse'); 
     }   
    } 

    function changePos(){ 
     var pos = { 
      "fixed": 992 
     }; 
    } 


    $(window).on('scroll', function(){ 
     if ($(window).scrollTop() > 50 && $(document).width() > 992){ 
      collapse('header', true); 

     } 
     else { 
      collapse('header'); 
     } 
    }); 

}); 

Resize事件不需要像你一樣嵌套,雖然我看到你在想什麼。相反,當滾動事件觸發時,使用JavaScript讀取文檔的寬度,而不是在重新調整大小事件時觸發。

然後我用CSS媒體查詢來控制固定位置,取決於屏幕寬度:

header { 
    background-color: red; 
    height: 200px; 
    transition: height .3s; 
    width: 100%; 
    top: 0; 
    left: 0; 

} 
main { 
    background-color: #abc; 
    height: 700px; 
} 
.collapse { 
    background: yellow !important; 
    height: 50px; 
    transition: height .3s; 
} 

@media all and (min-width: 992px) { 
     header { 
     position: relative; 
     background: blue; 
    } 
} 

@media all and (max-width: 992px) { 
header { 
     position: fixed; 
    } 
} 

希望這有助於!

修訂 http://jsfiddle.net/19fmc8wa/6/

+0

頭塌陷的小寬度。它不能。永久的必須工作沒有頁面刷新 –

+0

固定,但你現在有一個新問題。當縮小標題元素的高度時,它會與scrollTop()值混淆,並基於此重複計算。 –