2016-07-27 283 views
1

當我向下滾動到我的網站時,我想讓我的標題降低其高度。所以我寫了這個代碼:調整窗口大小Jquery

function resizeHeader() { 
    if ($(window).width() > 1200) { 
     if ($('body').hasClass('scrolled')) { 
      $('#masthead .top-header').css('height', '50px'); 
     } else { 
      //Initial height 
      $('#masthead .top-header').css('height', 'auto'); 
     } 
    } else if ($(window).width() > 768 && $(window).width() < 989) { 
     if ($('body').hasClass('scrolled')) { 
      $('#masthead .top-header').css('height', '35px'); 
     } else { 
      $('#masthead .top-header').css('height', 'auto'); 
     } 
    } 
} 

/** Fix header scroll **/ 
$(window).scroll(function() { 
    if ($(this).scrollTop() > 1) { 
     $('body').addClass('scrolled'); 
     resizeHeader(); 
    } else { 
     $('body').removeClass('scrolled'); 
     resizeHeader(); 
    } 
}); 

所以此代碼的工作,當我刷新我的網頁在想要的大小,腳本工作。

然而,當我刷新,然後我調整我的窗口,那麼我的頭有沒有我這個大小設置高度

我想,當我調整我的窗口,該功能正在運行,並做動作。它在刷新我的頁面時總是在工作,而不是在調整它的大小時。

感謝您的幫助!

+0

正如Rory所建議的那樣,您最好使用[CSS媒體查詢](https://developer.mozilla.org/en-US/docs/Web/CSS/Media_Queries/Using_media_queries) –

回答

2

您需要在加載頁面時觸發scroll事件,以便運行代碼。試試這個:

$(window).scroll(function() { 
    // your code here... 
}).trigger('scroll'); // < trigger on load 

另外請注意,這將是更爲合適的使用媒體查詢,像這樣把你resizeHeader()功能的邏輯中,以一個負責任的CSS樣式表:

#masthead .top-header { 
    height: auto; 
} 

@media (max-width: 1200px) { 
    .scrolled #masthead .top-header { 
    height: 50px; 
    } 
} 

@media (max-width: 989px) { 
    .scrolled #masthead .top-header { 
    height: 35px; 
    } 
} 
var scrollTimer; 
$(window).scroll(function() { 
    clearTimeout(scrollTimer); 
    scrollTimer = setTimeout(function() { 
     $('body').toggleClass('scrolled', $(this).scrollTop() > 1); 
    }, 250); 
}).trigger('scroll'); 
+0

我認爲OP希望綁定resize事件確實:「我想要的是當我調整窗口大小時,函數正在運行並執行操作 –

+0

是的,我忘了我可以通過響應媒體查詢來實現這一點,我正在嘗試這個解決方案 –

+0

是的它適用於媒體查詢。非常感謝提醒! –