核心思路
使用 readonly
属性替代 pointer-events: none
,既禁止用户编辑又允许表单提交值。
实现代码
<input type="text" id="recDate" name="recDate" readonly
class="input-text Wdate" style="width:240px;background-color:#f5f5f5;"
onfocus="this.blur()" />
<button onclick="setToday()">设为今天</button>
<button onclick="setTomorrow()">设为明天</button>
<script>
function setToday() {
const today = new Date();
document.getElementById('recDate').value = today.toISOString().split('T')[0];
}
function setTomorrow() {
const tomorrow = new Date();
tomorrow.setDate(tomorrow.getDate() + 1);
document.getElementById('recDate').value = tomorrow.toISOString().split('T')[0];
}
</script>
关键点说明
- 使用
readonly
属性替代禁用点击的方案 - 添加
onfocus="this.blur()"
防止获得焦点 - 设置背景色提示用户不可编辑
- 提供按钮让用户通过其他方式设置值
- 表单提交时该字段值会被正常提交
这种方法比使用 pointer-events: none
或 disabled
属性更合适,因为它既满足了禁止编辑的需求,又不会影响表单提交。