要实现日期输入框的光标自动跳转和占位符自动删除,可以通过JavaScript和HTML结合来实现。以下是一个简单的实现方案:
首先,创建一个包含多个输入框的HTML结构,每个输入框用于输入日期的不同部分(如年、月、日)。
<input type="text" id="year" maxlength="4" placeholder="YYYY" oninput="moveCursor('year', 'month', 4)">
<input type="text" id="month" maxlength="2" placeholder="MM" oninput="moveCursor('month', 'day', 2)">
<input type="text" id="day" maxlength="2" placeholder="DD" oninput="moveCursor('day', null, 2)">
编写JavaScript函数来处理光标跳转和占位符删除。
function moveCursor(currentId, nextId, maxLength) {
const currentInput = document.getElementById(currentId);
const nextInput = nextId ? document.getElementById(nextId) : null;
// 删除占位符
if (currentInput.value.length > 0) {
currentInput.placeholder = '';
} else {
currentInput.placeholder = currentId === 'year' ? 'YYYY' : currentId === 'month' ? 'MM' : 'DD';
}
// 自动跳转到下一个输入框
if (currentInput.value.length >= maxLength && nextInput) {
nextInput.focus();
}
}
id
,并且设置了maxlength
属性来限制输入的长度。oninput
事件监听输入框的内容变化,并调用moveCursor
函数。moveCursor
函数接收三个参数:当前输入框的id
、下一个输入框的id
(如果没有下一个输入框则为null
),以及当前输入框的最大长度。<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>日期输入框自动跳转</title>
</head>
<body>
<input type="text" id="year" maxlength="4" placeholder="YYYY" oninput="moveCursor('year', 'month', 4)">
<input type="text" id="month" maxlength="2" placeholder="MM" oninput="moveCursor('month', 'day', 2)">
<input type="text" id="day" maxlength="2" placeholder="DD" oninput="moveCursor('day', null, 2)">
<script>
function moveCursor(currentId, nextId, maxLength) {
const currentInput = document.getElementById(currentId);
const nextInput = nextId ? document.getElementById(nextId) : null;
// 删除占位符
if (currentInput.value.length > 0) {
currentInput.placeholder = '';
} else {
currentInput.placeholder = currentId === 'year' ? 'YYYY' : currentId === 'month' ? 'MM' : 'DD';
}
// 自动跳转到下一个输入框
if (currentInput.value.length >= maxLength && nextInput) {
nextInput.focus();
}
}
</script>
</body>
</html>
通过这种方式,你可以实现一个用户友好的日期输入框,自动跳转光标并删除占位符,提升用户体验。