javascript - 如何动态/响应式更改 jQuery 日期选择器的月数

标签 javascript jquery dynamic responsive-design datepicker

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

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

如果屏幕大小低于某个数字(例如 768px),我希望它为 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 的所有“临时”调用,我们实际上只关心最后一个调用,它是由最后一个调整大小事件触发的,它应该反射(reflect)用户停止的最终大小。

关于javascript - 如何动态/响应式更改 jQuery 日期选择器的月数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35847066/

相关文章:

php - Jquery - 无法自动选择从回调派生的特定选项

html - Dojo dijit 动态添加 Div 按钮

javascript - 仅在可见时加载图像?

javascript - 检查整数值是否是线性序列的一部分?

jquery - 获取自定义属性的值

c - 使用 DMA 打印给定值

javascript:动态调用嵌套函数

javascript - 修复旋转元素内的文本方向

Javascript 修改当前 URL?

javascript - 如何使用 jQuery 选择第一个父 DIV?