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

Cách đặt kích thước hình nền với JavaScript?

Sử dụng backgroundSize để đặt kích thước hình nền (cover, contain, px, %).

Ví dụ

<!DOCTYPE html>
<html>
  <head>
    <style>
      #box { border: 2px dashed blue; width: 600px; height: 400px; background: url('https://www.tutorialspoint.com/videotutorials/images/coding_ground_home.jpg') no-repeat; }
    </style>
  </head>
  <body>
    <button onclick="display()">Đặt kích thước hình nền</button>
    <div id="box"></div>
    <script>
      function display() {
        document.getElementById("box").style.backgroundSize = "150px 200px";
      }
    </script>
  </body>
</html>