CSS 資料型別 - <time>



CSS 的 <time> 資料型別表示一段時間。它用於需要時間值的屬性,例如 animation-durationtransition-duration 和其他一些屬性。<time> 的值可以用秒 (s)、毫秒 (ms) 或其他時間單位指定。

可能的值

以下單位可用於 <time> 資料型別

  • s - 表示以秒為單位的時間間隔。

  • ms - 表示以毫秒為單位的時間間隔。

語法

<number>unit

<time> 資料型別中的 <number> 後面是上面提到的特定單位。可以選擇在其前面新增單個 +- 符號。

單位文字和數字不應分開,就像其他維度一樣。

CSS <time> - 有效語法

以下是有效時間的列表

時間 描述
19.6 正整數
-123ms 負整數。
2.6ms 非整數
10mS 雖然不需要使用大寫字母,但單位不區分大小寫。
+0s 帶單位和前導 + 的零
-0ms 零、單位和前導 -

CSS <time> - 無效語法

以下是無效時間的列表

時間 描述
0 對於 <time>,無單位的零無效,但對於 <length> 則允許。
14.0 這缺少單位,因此它是 <number> 而不是 <time>。
9 ms 數字和單位之間不允許有空格。

CSS <time> - 有效/無效時間檢查

以下示例允許您檢查提供的輸入是有效時間還是無效時間

<html>
<head>
<style>
   body {
      font-family: Arial, sans-serif;
   }
   .container {
      width: 50%;
      margin: 50px auto;
      text-align: center;
   }
   label {
      margin-right: 10px;
   }
   input {
      padding: 5px;
      margin-right: 10px;
   }
   button {
      padding: 5px 10px;
      cursor: pointer;
   }
   #result {
      margin-top: 20px;
      font-weight: bold;
   }
</style>
</head>
<body>
<div class="container">
   <h2>Time Input Validation</h2>
   <form id="timeForm">
      <label for="timeInput">Enter a time:</label>
      <input type="text" id="timeInput" name="timeInput" placeholder="e.g., 5s or -200ms or 10mS">
      <button type="button" onclick="validateTime()">Check</button>
   </form>
   <p id="result"></p>
</div>
<script>
   function validateTime() {
      const userInput = document.getElementById('timeInput').value.trim();
      // Regular expressions to match valid time inputs
      const validTimeRegex = /^(0|(\+|-)?\d+(\.\d+)?(s|ms))$/i;
      if (validTimeRegex.test(userInput)) {
         document.getElementById('result').innerText = 'Valid time input!';
      } 
      else {
         document.getElementById('result').innerText = 'Invalid time input!';
      }
   }
</script>
</body>
</html>

CSS <time> - 與 transition-duration 一起使用

在 CSS 中的 transition-duration 中使用時,<time> 資料型別定義過渡效果的持續時間,指示過渡完成需要多長時間。

它可以精確控制 CSS 過渡的時間,並可以用毫秒或秒定義。

<html>
<head>
<style>
   button {
      transition-property: background-color, color, transform;
      transition-duration: 3s;
      transition-timing-function: cubic-bezier(0.25, 0.46, 0.45, 0.94);
      background-color: #2ecc71;
      color: white;
      border: none;
      padding: 15px 30px;
      font-size: 18px;
      cursor: pointer;
      border-radius: 8px;
      outline: none;
      box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
   }
   button:hover {
      background-color: #3498db; 
      color: #fff;
      transform: translateY(-3px); 
      box-shadow: 0 6px 8px rgba(0, 0, 0, 0.15); 
   }
</style>
</head>
<body>
<button>Hover Over This Button for 3 seconds</button>
</body>
</html>
廣告