我问这个问题是因为我找不到另一个答案。如果有,请链接到我。

我有一个jQuery Datepicker,在上面设置了参数numberOfMonths:2

如果screenSize低于某个数字(例如768像素),我希望它为1。我试过了:

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

但是由于日期选择器已经初始化,因此无法使用。

我能做什么?

最佳答案

您的工作方向正确,但是有足够的事情可以证明对我想发表完整的答案很有帮助。

首先,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);
  }

});

如果您不熟悉“Debounce”的概念,请使用see this article。其概念是防止代码在事件的每个实例上运行。在这种情况下,调整500像素大小可能会触发“调整大小”事件几百次,如果我们不进行“反跳”操作,那么datepicker函数将被调用数百次。显然,我们并不关心对datepicker的所有“临时”调用,我们实际上仅关心由上一次resize事件触发的最后一个,它应该反射(reflect)用户停止的最终大小。

10-07 19:06
查看更多