Thuộc tính style.transitionDuration trong HTML DOM quy định **thời gian diễn ra** của hiệu ứng chuyển tiếp (transition) — bao lâu để từ trạng thái đầu đến trạng thái cuối. Đơn vị: giây (s) hoặc millisecond (ms).
Cú pháp
// Lấy giá trị
var dur = element.style.transitionDuration;
// Đặt giá trị
element.style.transitionDuration = "500ms"; // hoặc "0.5s", "1s", "initial", "inherit"
Các giá trị
| Giá trị |
Giải thích |
0s (mặc định) |
Không có transition (thay đổi tức thì) |
<time> |
Thời lượng: 1s, 500ms, 2.5s. Có thể liệt kê nhiều cho nhiều property: 1s, 2s, 0.5s. |
inherit |
Kế thừa từ cha |
initial |
Trở về 0s |
Ví dụ: Kéo dài transition lên 5 giây
<!DOCTYPE html>
<html>
<style>
body { color: #000; height: 100vh; }
.btn { background: #db133a; border: none; height: 2rem; border-radius: 2px; width: 40%; display: block; color: #fff; outline: none; cursor: pointer; margin: 1rem 0; }
.circle {
width: 100px; height: 100px; background: #db133a;
margin: 2rem auto; transition: all 1s; /* Mặc định 1s */
}
.circle:hover {
width: 200px; height: 200px; border-radius: 50%;
}
.show { font-size: 1.2rem; margin: 1rem 0; text-align: center; }
<body>
<h1>Demo: transitionDuration</h1>
<div class="circle" id="circle"></div>
<button onclick="setDuration()" class="btn">Đặt duration 5s</button>
<div class="show">Hover vào hình tròn sau khi nhấn nút</div>
<script>
function setDuration() {
document.getElementById('circle').style.transitionDuration = "5s";
}
</script>
</body>
</html>
Kết quả:
- Ban đầu: Hover → chuyển đổi trong 1 giây.
- Nhấn nút: Set
duration = 5s.
- Hover lại: Chuyển đổi **rất chậm**, kéo dài 5 giây — thấy rõ từng khung hình.
Khi nào dùng duration bao lâu?
| Thời lượng |
Phù hợp cho |
100-200ms |
Feedback tức thì: hover button, focus input, toggle checkbox |
200-400ms |
Chuyển trạng thái UI: mở/đóng dropdown, modal, tab, accordion |
400-800ms |
Chuyển trang, slide panel, carousel, loading skeleton |
>1s |
Effect đặc biệt: hero animation, onboarding, game |
Lưu ý
- Duration **không bao gồm delay** — tổng thời gian = delay + duration.
- Nếu số duration < số property trong
transitionProperty, các property sau dùng duration cuối cùng.
element.style.transitionDuration chỉ inline style. Dùng getComputedStyle để đọc từ CSS.
- Quá lâu (>1s) khiến UI cảm giác "lag", user tưởng bị đơ — tránh cho interaction thường xuyên.
Shorthand transition
transition: width 500ms ease, height 500ms ease, opacity 200ms linear;