当 jQuery DatePicker 在 Bootstrap 弹出窗口(如模态框)中不起作用时,通常是由以下几个原因导致的:
确保 DatePicker 的 z-index 高于模态框:
.ui-datepicker {
z-index: 99999 !important;
}
确保在模态框完全显示后再初始化 DatePicker:
$('#myModal').on('shown.bs.modal', function() {
$('.datepicker').datepicker({
format: 'yyyy-mm-dd',
autoclose: true
});
});
避免 DatePicker 被限制在模态框内:
$('.datepicker').datepicker({
format: 'yyyy-mm-dd',
autoclose: true,
appendTo: 'body' // 关键选项
});
<!DOCTYPE html>
<html>
<head>
<title>DatePicker in Bootstrap Modal</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.9.0/css/bootstrap-datepicker.min.css">
<style>
.ui-datepicker {
z-index: 99999 !important;
}
</style>
</head>
<body>
<!-- 按钮触发模态框 -->
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#myModal">
打开模态框
</button>
<!-- 模态框 -->
<div class="modal fade" id="myModal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">选择日期</h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<div class="modal-body">
<input type="text" class="form-control datepicker" placeholder="选择日期">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">关闭</button>
</div>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.9.0/js/bootstrap-datepicker.min.js"></script>
<script>
$(document).ready(function() {
$('#myModal').on('shown.bs.modal', function() {
$('.datepicker').datepicker({
format: 'yyyy-mm-dd',
autoclose: true,
todayHighlight: true,
appendTo: 'body'
});
});
});
</script>
</body>
</html>
通过以上方法,应该能够解决 jQuery DatePicker 在 Bootstrap 弹出窗口中不起作用的问题。
没有搜到相关的文章