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

Thuộc tính background trong HTML DOM Style

Thuộc tính background là shorthand mạnh mẽ, cho phép đặt cùng lúc tới 8 thuộc tính nền: color, image, repeat, attachment, position, size, origin, clip.

Cú pháp

object.style.background = "color image repeat attachment position size origin clip|initial|inherit"

Các thành phần

Thứ tựThuộc tínhMô tả
1colorMàu nền.
2imageHình nền (url).
3repeatChế độ lặp.
4attachmentscroll/fixed/local.
5positionVị trí khởi đầu.
6sizeKích thước (cover, contain...).
7originVùng gốc (padding-box...).
8clipVùng vẽ (border-box...).

Ví dụ

Thay đổi hình nền div (chỉ demo thay image):

<!DOCTYPE html> <html> <head> <style> 
  #PIC { 
    width: 250px; 
    height: 150px; 
    border: solid 3px black; 
    font-weight: 100; 
    text-align: center; 
    color: white; 
    font-size: 40px; 
    background: url("https://www.tutorialspoint.com/python/images/python-mini.jpg") no-repeat fixed 2% 8%; 
  } 
</style> 
<script> 
  function changeBackground(){ 
    document.getElementById("PIC").style.backgroundImage = "url(https://www.tutorialspoint.com/csharp/images/csharp-mini-logo.jpg)"; 
    document.getElementById("Sample").innerHTML = "URL hình nền đã thay đổi"; 
  } 
</script> </head> 
<body> 
<h2>Học tập vui vẻ</h2> 
<div id="PIC">Tutorial</div> 
<p>Nhấn nút để đổi hình nền</p> 
<button onclick="changeBackground()">THAY ĐỔI BACKGROUND</button> 
<p id="Sample"></p> 
</body> </html>

Kết quả

Hình nền ban đầu (Python logo):

Thuộc tính background trong HTML DOM Style

Sau khi nhấn nút (C# logo):

Thuộc tính background trong HTML DOM Style