使用 numberOfMonths 时 jQuery UI 日期选择器的宽度:[2, 6]

Width of jQuery UI datepicker when using numberOfMonths: [2, 6]

我目前正在试验来自 jQuery UI 的 DatePicker 小部件。 我正在使用 jQuery UI 版本 1.11.4

我已经下载了 jQuery UI 的示例文件,其中包含 index.html 中所有小部件的简短演示。 日期选择器的 html 代码是这样的:

   <!-- Datepicker -->
   <h2 class="demoHeaders">Datepicker</h2>
   <div id="datepicker"></div>

我想在日期选择器中显示 12 个月以将其用作日历。 我尝试了两种配置:


配置 A 工作正常:

     $( "#datepicker" ).datepicker({
         numberOfMonths: [3, 4],
     });

但是我的配置 B 有问题

   $( "#datepicker" ).datepicker({
       numberOfMonths: [2, 6],
   });

这里日期选择器的宽度似乎比需要的要大,这导致灰色背景太靠右了。我放了一个 '?'到那个区域。

在 Chrome 开发工具中,我可以看到应用了 类 和 css。似乎样式中的宽度可能是原因,但这是由 jQuery.

生成的
<div class="ui-datepicker-inline ui-datepicker ui-widget ui-widget-content 
ui-helper-clearfix ui-corner-all ui-datepicker-multi-6 ui-datepicker-multi" 
style="width: 102em; display: block;">

演示:

<!DOCTYPE html>
<html>
<head>
<link href="https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css" rel="stylesheet" type="text/css" />
<script src="https://code.jquery.com/jquery-1.11.3.js"></script>
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>jQuery UI Datepicker - Display multiple months</title>
  <link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
  <script src="//code.jquery.com/jquery-1.10.2.js"></script>
  <script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
  <link rel="stylesheet" href="/resources/demos/style.css">
  <script>
  $(function() {
    $( "#datepicker" ).datepicker({
      numberOfMonths: [2,6],
      showButtonPanel: true
    });
  });
  </script>
</head>
<body>
 
<p>Date: <input type="text" id="datepicker"></p>
 
 
</body>
</html>
</body>
</html>

能否以某种方式帮助我在 6 个月内显示 2 行且宽度没有错误?谢谢。


在 jsfiddle 中查看:

你也可以在这里看到:jsfiddle.net/tvm6jrf5/1/

在尝试了不同的可能解决方案后,我找到了最适合我的解决方案,所以我在这里回答我自己的问题。

如上所述,主要问题是 JQuery UI 使用内联样式应用宽度。

<div class="ui-datepicker-inline ui-datepicker ui-widget ui-widget-content 
ui-helper-clearfix ui-corner-all ui-datepicker-multi-6 ui-datepicker-multi" 
style="width: 102em; display: block*;"

因此无法使用 CSS 解决此问题,因为日期选择器的内联样式不会应用 CSS:


解决方案 1:在运行时动态删除样式

这是我的第一个方法:

$("#calendar .ui-datepicker-inline").removeAttr("style");

我有一个 ID 为 "calendar" 的 div,其中放置了 JQuery 日期选择器。所以我使用此 JQuery 命令删除样式属性运行时间。

另外我写了一些css来自己设置宽度:

#calendar .ui-datepicker-inline {
    display: block;
    width: 100%;
}

起初这似乎可行,但有些事件会导致重新应用原来错误的宽度(例如选择日期、刷新小部件等)。 我意识到我不想为每个事件一次又一次地动态删除样式。


解决方案 2:更改 JQuery UI 创建样式的代码

我最终决定修复 JQuery UI 中导致此问题的代码,即生成具有宽度的样式的代码。

它可以在 JQuery UI 源文件中的 _updateDatepicker 函数中找到。

我更改了以下内容:

之前:

inst.dpDiv.addClass("ui-datepicker-multi-" + cols).css("width", (width * cols) + "em");

之后:

inst.dpDiv.addClass("ui-datepicker-multi-" + cols);

这样做的想法来自 JQuery 论坛中的 this 个帖子,其中一位用户遇到了同样的问题。