【问题标题】:How to add tooltip in jQuery Date Picker for disabled dates?如何在 jQuery 日期选择器中为禁用日期添加工具提示?
【发布时间】:2021-01-31 04:59:12
【问题描述】:

我正在处理网络表单,需要将日期选择限制在特定范围内,需要禁用其余日期。我已经使用 jquery-ui 实​​现了 datepicker。

要求

  1. 需要在禁用日期显示工具提示
  2. 过去和未来的日期都需要不同的工具提示

问题

我找到了显示工具提示的解决方案,目前仅在允许日期时才显示工具提示。我的意思是,如果beforeShowDay 返回true(允许选择日期),那么它会显示工具提示,否则由于某些原因它不会显示。但我只在禁用日期需要它。

示例代码

$( "#datepicker" ).datepicker({
    minDate: 0,
    maxDate: '+5D',
    beforeShowDay: function(date) {
        var sDate = new Date("2020-10-16").toDateString();
        var newDate = date.toDateString();
        
        if(sDate == newDate){
            // problem lies here
            return [false, '', 'sdate equals'];
            
            // this does work but it allows date selection, which I don't need
            // return [true, '', 'sdate equals'];
        }else{
            return [true, '', ''];
        }
    },
});
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>  
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>


<input type="text" id="datepicker" />

问题

  1. 如何仅显示禁用日期的工具提示?
  2. 如何为过去和未来的日期创建不同的工具提示?

【问题讨论】:

  • 您说“目前只有在允许日期时才显示工具提示”,这在 sn-p 中不起作用。你在使用 jQuery 工具提示吗?
  • 问题是disabled 用于禁用日期,这意味着没有触发DOM事件来显示工具提示。这似乎是a known limitation that jQuery recognizes。如果您使用浏览器的工具检查日历元素 DOM,您将看到元素标题 设置为 sdate equals 值,但不会呈现显示。
  • @melvin 是的,我使用的是默认的 jQuery 工具提示。
  • @PaulT。嗯,有什么解决办法吗?

标签: jquery jquery-ui datepicker tooltip jquery-ui-datepicker


【解决方案1】:

您可以通过添加ui-datepicker-unselectable 类来实现结果,它将禁用日期选择但不会禁用DOM 中的整个元素,因此可以显示工具提示。您可以通过添加几行 css 来获得禁用元素的外观。

$( "#datepicker" ).datepicker({
    beforeShowDay: function(date) {
    
        // assuming you want to start from today
        var startDate = new Date();
        
        // assuming end date 5 days in the future
        var endDate = new Date().setDate(new Date().getDate() + 5);
        
        if(date < startDate){
            return [true, 'ui-datepicker-unselectable', 'past date'];
        }else if(date > endDate){
            return [true, 'ui-datepicker-unselectable', 'future date'];
        }else{
            return [true, '', ''];
        }
    },
});
.ui-datepicker-unselectable a{
  opacity: 0.4;
  pointer-events: none;
}
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>  
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>


<input type="text" id="datepicker" />

PS:上面的代码 sn-p 中提供了您两个问题的答案。

干杯!

【讨论】:

  • 感谢您提供的解决方法示例。我没有机会研究解决方法,因为我从未在日历中使用过工具提示。
  • @Atlas_Gondal 非常感谢您提供的解决方案,它非常干净并且按照需要的方式工作!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-29
  • 2019-03-30
  • 1970-01-01
  • 2014-11-10
  • 2018-05-28
相关资源
最近更新 更多