你走在正確的軌道上,但有足夠的東西可以證明是有用的,我想發佈一個完整的答案。
首先,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的「臨時」調用,我們只關心最後一個調用大小事件觸發的最後一個調整事件,它應該反映用戶停留的最終大小。