Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> HTML

Thuộc tính transitionProperty của Style trong HTML DOM

Thuộc tính style.transitionProperty trong HTML DOM quy định **tên các thuộc tính CSS** sẽ được áp dụng hiệu ứng chuyển tiếp (transition). Chỉ các property liệt kê ở đây mới được animate khi giá trị thay đổi.

Cú pháp

// Lấy giá trị
var props = element.style.transitionProperty;

// Đặt giá trị
element.style.transitionProperty = "width, height, background-color";

Các giá trị

Giá trị Ý nghĩa
all (mặc định) Áp dụng transition cho **tất cả** property có thể animate (khuyến khích chỉ định rõ để tối ưu hiệu năng)
none Không property nào được transition
<property-name> Danh sách tên property cách nhau bởi dấu phẩy: width, transform, opacity, background-color, color, margin...
inherit Kế thừa từ cha
initial Trở về all

Ví dụ: Chỉ transition border-radius

<!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 all */
  }
  .circle:hover {
    width: 200px; height: 200px; border-radius: 50%;
  }
  .show { font-size: 1.2rem; margin: 1rem 0; text-align: center; }

<body>
  <h1>Demo: transitionProperty</h1>
  <div class="circle" id="circle"></div>
  <button onclick="setProp()" class="btn">Chỉ transition border-radius</button>
  <div class="show">Hover vào hình tròn sau khi nhấn nút</div>
  <script>
    function setProp() {
      document.getElementById('circle').style.transitionProperty = "border-radius";
      // Chỉ border-radius được animate, width/height thay đổi tức thì
    }
  </script>
</body>
</html>

Kết quả:

  1. Ban đầu (transition: all 1s): Hover → width, height, border-radius **cùng animate** 1s.
  2. Sau nhấn nút (transition-property: border-radius): Hover → width/height **nhảy ngay** về 200px, chỉ border-radius **animate 1s** từ vuông sang tròn.

Tối ưu hiệu năng: Chỉ animate property rẻ

Rẻ (GPU-friendly) Đắt (Layout/Repaint)
transform (translate, scale, rotate) width, height, margin, padding, top, left...
opacity color, background-color, border, box-shadow...
filter font-size, line-height, text-shadow...

Khuyên dùng: transition-property: transform, opacity; — mượt nhất, không gây reflow.

Lưu ý

  • transitionProperty chỉ inline style. Dùng getComputedStyle(el).transitionProperty để đọc từ CSS.
  • Property không thể animate (ví dụ display, visibility) sẽ bị bỏ qua.
  • Kết hợp với transitionDuration, transitionTimingFunction, transitionDelay hoặc shorthand transition.