如何在 jQuery 日期选择器中为禁用日期添加工具提示?

How to add tooltip in jQuery Date Picker for disabled dates?

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

实现了日期选择器

请求ui评论:

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

问题:

我找到了显示工具提示的解决方案,目前只有在允许日期时才显示工具提示。我的意思是,如果 beforeShowDay returns 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. 如何为过去和未来的日期创建不同的工具提示?

您可以通过添加 ui-datepicker-unselectable class 来实现结果,它将禁用日期选择但不会禁用 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: 你的两个问题的答案都可以在上面的代码片段中找到。

干杯!

jQuery UI 在其禁用元素上使用 CSS 来关闭显示工具提示所需的指针事件。要在禁用日期显示工具提示,您需要做的就是添加此 CSS 以覆盖 jQuery UI.

html .ui-datepicker .ui-state-disabled {
    pointer-events: auto;
}