HTML5 – 日期
在 HTML5 標準中,日期輸入框得到了大幅度的改進和增強。愛掏網 - it200.com現在,無需使用 JavaScript 選擇日期,只需在輸入框中鍵入日期即可。愛掏網 - it200.com
最基本的日期輸入框如下所示:
<label for="birthday">出生日期:</label>
<input type="date" id="birthday" name="birthday">
這個輸入框將顯示一個日期選擇器。愛掏網 - it200.com在支持 HTML5 標準的現代瀏覽器上,用戶可以打開日期選擇器并選擇日期。愛掏網 - it200.com如果瀏覽器不支持 HTML5 標準,則該輸入框將顯示為文本框,用戶可以手動輸入日期。愛掏網 - it200.com
除了日期輸入框之外,還有時間輸入框,它們的標簽分別是 <input type="time">
和 <input type="datetime-local">
。愛掏網 - it200.com
<label for="appt">預約時間:</label>
<input type="time" id="appt" name="appt">
<label for="meeting">會議時間:</label>
<input type="datetime-local" id="meeting" name="meeting">
這兩個輸入框分別顯示了時間選擇器和日期時間選擇器。愛掏網 - it200.com
另外,還有一個帶有范圍限制的日期輸入框,它允許您指定不能選擇的日期范圍。愛掏網 - it200.com
<label for="start">開始日期:</label>
<input type="date" id="start" name="start" min="2022-01-01" max="2022-12-31">
這個輸入框將始終顯示 2022 年的日期范圍,用戶不能選擇此范圍之外的日期。愛掏網 - it200.com
自定義日期輸入框樣式
標準的日期輸入框可能無法滿足所有需求。愛掏網 - it200.com您可以使用 CSS 來自定義輸入框的外觀。愛掏網 - it200.com下面是一個示例,采用了一些較為常見的自定義樣式:
<style>
input[type="date"] {
background-color: #fff;
border: 1px solid #dcdfe6;
border-radius: 2px;
padding: 8px;
outline: none;
height: 32px;
font-size: 14px;
color: #606266;
}
</style>
<label for="eventdate">活動日期:</label>
<input type="date" id="eventdate" name="eventdate">
樣式表將一般的輸入框樣式轉換為了具有不同背景和邊框樣式的個性化輸入框。愛掏網 - it200.com您可以進一步自定義樣式以適應你的網站設計。愛掏網 - it200.com
獲取和設置日期值
為了獲取和設置日期輸入框的值,您可以使用 JavaScript。愛掏網 - it200.com以下是一個獲取日期輸入框值的示例:
const input = document.getElementById("birthday");
input.addEventListener("change", () => {
const value = input.value;
console.log(value); // 2022-07-31
});
這段代碼監聽了輸入框的 change 事件,并在值改變時打印出日期。愛掏網 - it200.com
要設置日期輸入框的默認值,請將值屬性設置為默認日期:
<label for="birthday">出生日期:</label>
<input type="date" id="birthday" name="birthday" value="2000-01-01">
這將在日期輸入框中顯示 2000 年 1 月 1 日。愛掏網 - it200.com
結論
HTML5 標準對日期和時間輸入框進行了大量的增強和改進,現在可以輕松地使用它們來選擇日期和時間。愛掏網 - it200.com您可以通過自定義樣式表輕松地將其個性化以適應您的設計需求。愛掏網 - it200.com在 JavaScript 中獲取和設置日期輸入框的值也變得非常容易。愛掏網 - it200.com