
2. 引入 moment.js 和 jquery
为了方便日期格式化和 DOM 操作,我们需要引入 Moment.js 和 jQuery 库。
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script> <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
3. JavaScript 代码
使用 JavaScript 监听 input 元素的 change 事件,并在事件处理函数中使用 Moment.js 格式化日期,然后将格式化后的日期存储到 data-date 属性中。
$("input").on("change", function() {
this.setAttribute(
"data-date",
moment(this.value, "YYYY-MM-DD")
.format( this.getAttribute("data-date-format") )
)
}).trigger("change")4. CSS 样式
立即学习“前端免费学习笔记(深入)”;
使用 CSS 隐藏原生的日期显示,并使用伪元素 :before 显示格式化后的日期。
input {
position: relative;
width: 150px;
height: 20px;
color: white; /* 隐藏原生日期文字 */
}
input:before {
position: absolute;
top: 3px;
left: 3px;
content: attr(data-date);
display: inline-block;
color: black; /* 设置格式化后的日期文字颜色 */
}
input::-webkit-datetime-edit,
input::-webkit-inner-spin-button,
input::-webkit-clear-button {
display: none; /* 隐藏原生日期编辑框 */
}
input::-webkit-calendar-picker-indicator {
position: absolute;
top: 3px;
right: 0;
color: black;
opacity: 1; /* 显示日历图标 */
}完整示例代码
<!DOCTYPE html>
<html>
<head>
<title>Custom Date Format</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<style>
input {
position: relative;
width: 150px;
height: 20px;
color: white; /* 隐藏原生日期文字 */
}
input:before {
position: absolute;
top: 3px;
left: 3px;
content: attr(data-date);
display: inline-block;
color: black; /* 设置格式化后的日期文字颜色 */
}
input::-webkit-datetime-edit,
input::-webkit-inner-spin-button,
input::-webkit-clear-button {
display: none; /* 隐藏原生日期编辑框 */
}
input::-webkit-calendar-picker-indicator {
position: absolute;
top: 3px;
right: 0;
color: black;
opacity: 1; /* 显示日历图标 */
}
</style>
</head>
<body>
<input type="date" data-date="" data-date-format="MM/DD/YYYY" value="2023-10-27">
<script>
$("input").on("change", function() {
this.setAttribute(
"data-date",
moment(this.value, "YYYY-MM-DD")
.format( this.getAttribute("data-date-format") )
)
}).trigger("change")
</script>
</body>
</html>虽然 HTML 原生的 <input type="date"> 元素不支持直接自定义日期格式,但通过结合 CSS 和 JavaScript,我们可以模拟出期望的显示效果。 这种方法需要在兼容性、性能和用户体验之间进行权衡,并根据实际需求进行选择。
以上就是HTML Date Input 格式化为 MM/DD/YYYY 的实现方法的详细内容,更多请关注php中文网其它相关文章!
HTML怎么学习?HTML怎么入门?HTML在哪学?HTML怎么学才快?不用担心,这里为大家提供了HTML速学教程(入门课程),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号