要选择日期范围,请使用Jquery UI Datepicker插件。我使用的代码可以显示选择期间的天数。
要连接插件,请使用CDN:
<script type="text/javascript" src='https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js'></script>
<script type="text/javascript" src='https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js'></script>
<link rel="stylesheet" type="text/css" href="https://jquery-ui-bootstrap.github.io/jquery-ui-bootstrap/css/custom-theme/jquery-ui-1.10.3.custom.css"></link>
HTML代码:
<div>
<h3>From:</h3>
<input id="from" type="text" name="from" readonly />
</div>
<div>
<h3>To:</h3>
<input id="to" type="text" name="to" readonly />
</div>
<div>
<span>You have chosen:</span>
<span id="days"></span> days.
</div>
插件初始化:
var from = new Date();
var to = new Date();
var dayDiff = 1;
$(function() {
var dates = $("#from, #to").datepicker({
defaultDate: "+1w",
changeMonth: true,
numberOfMonths: 1,
dateFormat: "dd.mm.yy",
minDate: 0,
maxDate: 14,
onSelect: function(selectedDate) {
var option = this.id == "from" ? "minDate" : "maxDate",
instance = $(this).data("datepicker"),
date = $.datepicker.parseDate(
instance.settings.dateFormat ||
$.datepicker._defaults.dateFormat,
selectedDate, instance.settings);
dates.not(this).datepicker("option", option, date);
if (this.id == "from") {
from = $(this).datepicker('getDate');
if (!(to == "")) {
update_days()
}
}
if (this.id == "to") {
to = $(this).datepicker('getDate');
update_days()
}
}
});
});
function update_days() {
dayDiff = Math.ceil((to - from) / (1000 * 60 * 60 * 24));
$("#days").empty()
$("#days").append(dayDiff)
}
如何动态选择天数?
例如,用户在4月1日点击了。仅显示他可以选择的14天。如果用户点击了4月7日,则还会显示14天可供选择。
在两种情况下,这都是minDate:0和maxDate:14,
我找到了类似的代码,只是在这里它禁止接下来7天的分配:
let counter = 0;
let selected;
const calendar = $("#datepicker").datepicker({
range: true,
toggleSelected: false,
multipleDatesSeparator: " - ",
multipleDates: false,
onSelect: function(formattedDate, date, inst) {
selected = date;
// console.log(selected[0])
},
// onRenderCell: function(date, cellType) {
// if (selected) {
// const difference = Math.ceil((date - selected[0]) / 1000 / 3600 / 24);
// console.log(difference)
// if (difference < 7 && difference > -7) {
// return {
// disabled: true
// }
// }
// }
// }
}).data('datepicker');
const test = function(date, cellType) {
if (selected) {
const difference = Math.ceil((date - selected[0]) / 1000 / 3600 / 24);
console.log(difference)
if (difference < 7 && difference > -7) {
return {
disabled: true
}
}
}
}
calendar.update('onRenderCell', test)
需要您的帮助!谢谢!