
这里,data-date-format属性指定了我们期望的日期格式。value属性的值必须是yyyy-mm-dd格式,这是html日期输入框的标准格式。
2. 引入依赖库
首先,需要在HTML文件中引入jQuery和moment.js库。
<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. CSS样式
使用CSS来隐藏原生日期输入框的样式,并创建一个伪元素来显示格式化后的日期。
立即学习“前端免费学习笔记(深入)”;
input {
position: relative;
width: 150px;
height: 20px;
color: white; /* 隐藏原生文字颜色 */
}
input:before {
position: absolute;
top: 3px;
left: 3px;
content: attr(data-date); /* 显示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; /* 显示日历图标 */
}4. JavaScript代码
使用JavaScript监听input事件,并使用moment.js格式化日期。
$("input").on("change", function() {
this.setAttribute(
"data-date",
moment(this.value, "YYYY-MM-DD").format( this.getAttribute("data-date-format") )
)
}).trigger("change");这段代码的含义是:
完整示例代码
<!DOCTYPE html>
<html>
<head>
<title>Date Input 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>注意事项
总结
通过结合CSS和JavaScript,我们可以模拟一个具有自定义格式的日期输入框,从而满足特定的需求。虽然这种方法有一定的局限性,但它提供了一种在无法直接修改原生日期输入框格式的情况下,实现自定义日期格式的有效途径。需要注意的是,这种方法主要是在视觉上模拟日期格式,并没有改变日期输入框的底层数据格式。
以上就是HTML日期输入框格式化为MM/DD/YYYY的实现方法的详细内容,更多请关注php中文网其它相关文章!
HTML怎么学习?HTML怎么入门?HTML在哪学?HTML怎么学才快?不用担心,这里为大家提供了HTML速学教程(入门课程),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号