Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

jQuery 日期時間選擇器 Datepicker 中文化設定完整教學

網頁表單只要涉及「填日期」或「填時間」,自己刻一個日曆面板總是事倍功半。jQuery UI 的 Datepicker 搭配 Timepicker Addon,就能一次搞定年月日與時分秒,而這套元件最常被詬病的缺點是預設全英文——好在官方提供了中文語系檔,引入之後介面立刻變得親切。

需要準備的檔案

原始範例的資源檔可從 Linux IDC 的免費下載專區取得(該站台下載帳號與密碼皆為 www.linuxidc.com),下載目錄為 /2012年資料/7月/30日/jQuery時間控件Datepicker漢化版使用詳解/。若偏好直接取用官方來源,專案首頁與 GitHub 倉庫如下:

  • 專案示範頁:https://trentrichardson.com/examples/timepicker/
  • GitHub:https://github.com/trentrichardson/jQuery-Timepicker-Addon

核心檔案包含 jQuery 本體、jquery-ui.min.js、時間元件的 jquery-ui-timepicker-addon.js、輔助用的 jquery-ui-sliderAccess.js,以及關鍵的中文語系檔 jquery-ui-timepicker-zh-CN.js;樣式則需要 jquery-ui.css 與 jquery-ui-timepicker-addon.css。

頁面組裝

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "https://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html lang="en" xmlns="https://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>日期時間選擇器範例</title>

    <link rel="stylesheet" media="all" type="text/css" href="css/jquery-ui.css" />
    <link rel="stylesheet" media="all" type="text/css"
          href="css/jquery-ui-timepicker-addon.css" />

    <script type="text/javascript" src="js/jquery-1.7.2.js"></script>
    <script type="text/javascript" src="js/jquery-ui.min.js"></script>
    <script type="text/javascript" src="js/jquery-ui-timepicker-addon.js"></script>
    <script type="text/javascript" src="js/jquery-ui-sliderAccess.js"></script>
    <script type="text/javascript" src="js/jquery-ui-timepicker-zh-CN.js"></script>

    <script type="text/javascript">
        $(function(){
            $('#example').timepicker({});
        });
    </script>

    <style type="text/css">
        #ui-datepicker-div, .ui-datepicker{ font-size: 80%; }
    </style>
</head>
<body>
    <input type="text" name="example" id="example" value="" />
</body>
</html>

整段程式的關鍵只有兩處:一是 引入順序,jQuery 必須在 jQuery UI 之前,語系檔則要排在 timepicker-addon 之後才會生效;二是 $('#example').timepicker({}) 這行初始化,空物件代表全部採用預設值。其中 jquery-ui-timepicker-zh-CN.js 就是讓「月、日、時、分、秒、現在、關閉」等文字變成中文的漢化檔。

常見的客製化需求

預設面板只到「分」,若需要秒,可寫成 $('#example').timepicker({ showSecond: true });只想選日期不選時間,改用 datepicker() 即可;想限制可選時段,則用 hourMin、hourMax 搭配 minTime、maxTime。最後那段 CSS 把日曆字級縮成 80%,是為了讓面板在小螢幕或窄欄位中不撐破版面,實作時可依設計稿調整。

Copyright © Linux教程網 All Rights Reserved