CSS 数据类型 <time> 表示持续时间。它用于需要时间值的属性,例如 animation-duration、transition-duration 和某些其他属性。<time> 的值可以以秒 (s)、毫秒 (ms) 或其他时间单位指定。
可能的值
以下单位可用于 <time> 数据类型:
- s - 表示以秒为单位的时间间隔。
- ms - 表示以毫秒表示的时间间隔。
语法
<number>unit
数据类型 <time> 中的 <number> 后跟上述特定单位。可以选择在它前面加上一个 + 或 - 符号。
单位字面量和数字不应该分开,就像在其他维度中一样。
CSS <time> - 有效语法
以下是有效时间列表:
Time | 描述 |
---|---|
19.6 | 正整数 |
-123ms | 负整数 |
2.6ms | 非整数 |
10mS | 虽然不必使用大写字母,但该单位不区分大小写。 |
+0s | 零,带有一个单位和一个前导 + |
-0ms | 零、一个单位和一个前导 - |
CSS <time> - 无效语法
以下是无效时间的列表:
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>