我正在使用 HTML5 输入日期,如下所示:
<input type="date" id="start" name="trip-start"
value="2018-07-22"
min="2020-03-01" max="2021-03-31">
Run Code Online (Sandbox Code Playgroud)
如果用户单击日期选择器图标,则日期限制有效,但如果用户在表单中键入,则日期限制无效。
也许我们可以使用 jquery 检查限制?但还没有尝试过。我将尝试在 jsfiddle 中工作,这里是链接:https ://jsfiddle.net/TheCuteCat/rcxjmse1/
我会做类似的事情:
//<![CDATA[
/* js/external.js */
let doc, htm, bod, nav, M, I, mobile, S, Q;
addEventListener('load', ()=>{
doc = document; htm = doc.documentElement; bod = doc.body; nav = navigator; M = tag=>doc.createElement(tag); I = id=>doc.getElementById(id);
mobile = nav.userAgent.match(/Mobi/i) ? true : false;
S = (selector, within)=>{
var w = within || doc;
return w.querySelector(selector);
}
Q = (selector, within)=>{
var w = within || doc;
return w.querySelectorAll(selector);
}
// tiny library above - magic below
const date = I('date'), minDate = new Date('3/1/2020'), millisecondOverMaxDate = new Date('4/1/2020');
date.onchange = function(){
const a = this.value.split('-'), s = a.shift(), d = new Date(a.join('/')+'/'+s), t = d.getTime();
console.clear(); // remove consoles on deployment
if(t >= minDate && t < millisecondOverMaxDate){
console.log('within range');
}
else{
console.log('out of range');
}
}
}); // end load
Run Code Online (Sandbox Code Playgroud)
/* css/external.css */
*{
box-sizing:border-box; color:#000; padding:0; margin:0; overflow:hidden;
}
html,body,.main{
width:100%; height:100%;
}
.main{
background:#333; overflow-y:auto;
Run Code Online (Sandbox Code Playgroud)
<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
<head>
<meta charset='UTF-8' /><meta name='viewport' content='width=device-width, height=device-height, initial-scale:1, user-scalable=no' />
<title>Title Here</title>
<link type='text/css' rel='stylesheet' href='css/external.css' />
<script src='js/external.js'></script>
</head>
<body>
<div class='main'>
<input id='date' type='date' value='2018-07-22' min='2020-03-01' max='2021-03-31' />
</div>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)