如何解决如何在jQuery Date Picker中为禁用日期添加工具提示?
我正在使用Web表单,需要将日期选择限制在特定范围内,需要禁用其余日期。我已经使用jquery-ui实现了datepicker。
要求:
- 需要在禁用日期显示工具提示
- 过去和将来的日期都需要不同的工具提示
问题:
我找到了显示工具提示的解决方案,并且当前只有在允许日期的情况下才显示工具提示。我的意思是,如果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" />
问题:
- 如何仅显示禁用日期的工具提示?
- 如何为过去和将来的日期创建不同的工具提示?
解决方法
您可以通过添加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,'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:以上两个代码段都提供了这两个问题的答案。
干杯!
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。