我问这个问题是因为我无法在另一个问题上找到答案。如果有,请链接到我。
我有一个jQuery Datepicker,我在其上设置参数numberOfMonths:2
如果screenSize低于某个数字(例如768px),我希望它为1。我试过了:
$(window).resize(function(){
if($(window).width() < 768){
$('#datepicker').datepicker({
numberOfMonths: 1
})
}
}
但是由于datepicker已经初始化,因此不起作用。
我该怎么办?
答案 0 :(得分:4)
你走在正确的轨道上,但是有足够的东西可以证明是有用的,我想要发表一个完整的答案。
这是我提出的代码,其中的注释解释了每个元素:
// "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);
}
});
如果您不熟悉&#34; Debounce&#34;,see this article的概念。这个概念是您阻止代码在事件的每个单个实例上运行。在这种情况下,500像素的大小调整可能会触发&#34;调整大小&#34;事件几百次,如果我们没有&#34; debounce&#34;,datepicker函数将被调用几百次。显然,我们并不关心所有&#34;临时&#34;调用datepicker,我们真的只关心最后一个,这是由最后一个调整大小事件触发的,它应该反映用户停止的最终大小。
答案 1 :(得分:1)
http://api.jqueryui.com/datepicker/#option-numberOfMonths
如果已经初始化了datepicker,则应使用选项setters:
$( "#datepicker" ).datepicker( "option", "numberOfMonths", [ 2, 3 ] );
参数也可以是数字,就像初始化它一样。查看链接以获取更多信息。