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

Cách đặt hình ảnh làm viền (borderImageSource) bằng JavaScript

Thuộc tính borderImageSource chỉ định hình ảnh dùng làm viền cho phần tử. Phải kết hợp với borderImageSlice (cắt ảnh), borderImageWidth (độ rộng viền), borderImageRepeat (cách lặp) để hoạt động đúng.

Ví dụ minh họa

Mã sau thay đổi hình ảnh viền từ neo4j.png sang bugzilla.png khi nhấn nút:

<!DOCTYPE html>
<html>
<head>
  <style>
    div {
      background-color: blue;
      color: white;
      border: 40px solid transparent; /* border-width > 0, style != none */
      border-image: url('https://www.tutorialspoint.com/images/neo4j.png');
      border-image-slice: 50;
      border-image-width: 1 1 1 1;
      border-image-outset: 0;
      border-image-repeat: round;
      padding: 20px;
      width: 300px;
      height: 150px;
    }
  </style>
</head>
<body>
  <div id="box">
    <p>Demo Text!</p>
  </div>
  <button onclick="changeBorderImage()">Đổi hình viền</button>
  <script>
    function changeBorderImage() {
      document.getElementById("box").style.borderImageSource =
        "url('https://www.tutorialspoint.com/images/bugzilla.png')";
      /* Chỉ đổi source, các slice/width/repeat giữ nguyên */
    }
  </script>
</body>
</html>

Quy trình border-image (9-slice scaling)

  1. Source: borderImageSource — URL hình ảnh hoặc gradient.
  2. Slice: borderImageSlice — Cắt ảnh thành 9 vùng: 4 góc, 4 cạnh, 1 giữa. Giá trị: offset từ cạnh (px hoặc %).
    • 1 giá trị: 4 cạnh cùng offset.
    • 4 giá trị: top right bottom left.
  3. Width: borderImageWidth — Độ rộng khu vực viền hiển thị (mặc định = border-width).
  4. Outset: borderImageOutset — Mở rộng khu vực viền ra ngoài border-box.
  5. Repeat: borderImageRepeat — stretch, repeat, round, space.

Shorthand borderImage

el.style.borderImage = "url('img.png') 30 / 10px / 0 round";
/* source slice / width / outset repeat */

Lưu ý: Hình ảnh giữa (center slice) **mặc định bị ẩn** (chỉ dùng làm background nếu có fill keyword trong slice). border-image không ảnh hưởng layout (không chiếm diện tích như border thường).