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

Cách đặt loại đường trang trí văn bản (textDecorationLine) bằng JavaScript

Thuộc tính textDecorationLine xác định loại đường trang trí: underline (gạch chân), overline (gạch trên), line-through (gạch ngang), blink (nhấp nháy - lỗi thời). Có thể kết hợp nhiều giá trị.

Ví dụ minh họa

Mã sau thêm gạch trên (overline) màu đỏ cho văn bản đã có gạch chân khi nhấn nút:

<!DOCTYPE html>
<html>
<body>
  <div id="myText" style="text-decoration: underline;">
    Đây là văn bản demo.
  </div>
  <br>
  <button onclick="setDecorationLine()">Đặt trang trí văn bản</button>
  <script>
    function setDecorationLine() {
      const el = document.getElementById("myText");
      el.style.textDecorationColor = "red";
      el.style.textDecorationLine = "overline";
      /* Kết hợp: "underline overline line-through" */
    }
  </script>
</body>
</html>

Các giá trị của textDecorationLine

Giá trị Hiển thị Dùng cho
noneKhông trang tríXóa trang trí (mặc định)
underlineGạch chânLink, nhấn mạnh
overlineGạch trênTiêu đề trang trí
line-throughGạch ngang giữaGiá cũ, nội dung xóa
blinkNhấp nháyĐã lỗi thời, trình duyệt bỏ qua

Kết hợp nhiều dòng

el.style.textDecorationLine = "underline overline";      // Cả trên và dưới
el.style.textDecorationLine = "underline line-through";  // Gạch chân + gạch ngang

Shorthand textDecoration (khuyên dùng)

el.style.textDecoration = "overline red wavy 2px";
/* line style color thickness */

Lưu ý: textDecorationLine là thành phần của shorthand textDecoration. Dùng shorthand để code gọn, dùng thuộc tính con khi cần override một phần.