2016-03-07 47 views
2

我在問這個問題,因爲我找不到另一個答案。如果有請將它鏈接到我。如何動態更改jQuery datepicker月數/響應

我有一個jQuery日期選擇器上,其餘設置的參數NUMBEROFMONTHS:2

我希望它是1,如果屏幕尺寸低於某一數目(例如768px)。我試過了:

$(window).resize(function(){ 
    if($(window).width() < 768){ 
     $('#datepicker').datepicker({ 
      numberOfMonths: 1 
     }) 
    } 
} 

但是由於datepicker已經被初始化,所以不起作用。

我能做些什麼?

回答

3

你走在正確的軌道上,但有足夠的東西可以證明是有用的,我想發佈一個完整的答案。

首先,Here's a working Fiddle

下面是我建議的代碼,以註釋解釋每個元素:

// "No-conflict" jQuery document ready, to ensure doesn't collide with other libraries 
jQuery(function($) { 
    // The initial datepicker load 
    $('#datepicker').datepicker({ 
    numberOfMonths: 3 
    }); 

    // We're going to "debounce" the resize, to prevent the datePicker 
    // from being called a thousand times. This will help performance 
    // and ensure the datepicker change is only called once (ideally) 
    // when the resize is OVER 
    var debounce; 
    // Your window resize function 
    $(window).resize(function() { 
    // Clear the last timeout we set up. 
    clearTimeout(debounce); 
    // Your if statement 
    if ($(window).width() < 768) { 
     // Assign the debounce to a small timeout to "wait" until resize is over 
     debounce = setTimeout(function() { 
     // Here we're calling with the number of months you want - 1 
     debounceDatepicker(1); 
     }, 250); 
    // Presumably you want it to go BACK to 2 or 3 months if big enough 
    // So set up an "else" condition 
    } else { 
     debounce = setTimeout(function() { 
     // Here we're calling with the number of months you want - 3? 
     debounceDatepicker(3) 
     }, 250); 
    } 
    // To be sure it's the right size on load, chain a "trigger" to the 
    // window resize to cause the above code to run onload 
    }).trigger('resize'); 

    // our function we call to resize the datepicker 
    function debounceDatepicker(no) { 
    $("#datepicker").datepicker("option", "numberOfMonths", no); 
    } 

}); 

如果你不熟悉的「防抖動」,see this article的概念。其概念是,您可以防止代碼在事件的每個實例上運行。在這種情況下,500像素的調整大小可能觸發幾百次「調整大小」事件,如果我們沒有「反彈」,datepicker函數將被調用幾百次。顯然,我們並不關心所有對datepicker的「臨時」調用,我們只關心最後一個調用大小事件觸發的最後一個調整事件,它應該反映用戶停留的最終大小。