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

Cách thiết lập tất cả thuộc tính outline trong một khai báo với JavaScript

Thuộc tính outline là shorthand đặt cùng lúc outline-width, outline-style, outline-color (thứ tự tùy ý).

Ví dụ minh họa

Nhấn nút đặt outline thick solid #5F5F5F:

<!DOCTYPE html>
<html>
<head>
  <style>
    #box {
      width: 450px;
      background-color: orange;
      border: 3px solid red;
      margin-left: 20px;
      padding: 10px;
    }
  </style>
</head>
<body>
  <p>Nhấn nút để thêm Outline.</p>
  <div id="box">
    <p>Đây là div. Đây là div. Đây là div. Đây là div. Đây là div.</p>
    <p>Đây là div. Đây là div. Đây là div. Đây là div. Đây là div.</p>
    <p>Đây là div. Đây là div. Đây là div. Đây là div. Đây là div.</p>
  </div>
  <br>
  <button type="button" onclick="display()">Đặt Outline</button>
  <br>
  <script>
    function display() {
      document.getElementById("box").style.outline = "thick solid #5F5F5F";
    }
  </script>
</body>
</html>

Cú pháp outline shorthand

outline: <width> <style> <color>

  • Có thể bỏ qua bất kỳ giá trị nào (dùng mặc định).
  • Ví dụ: outline: 2px dashed red, outline: solid, outline: #00f.

Không thể đặt outline-offset trong shorthand

outline-offset là thuộc tính riêng, không nằm trong shorthand outline.

Ứng dụng thực tế: Focus ring accessible

:focus-visible {
  outline: 2px solid #0066cc;
  outline-offset: 2px;
}

Đảm bảo tuân thủ WCAG 2.4.7 Focus Visible.