HTML DOM 样式 backgroundImage 属性

htmlweb developmentfront end technology更新于 2025/9/29 16:12:17

backgroundImage 属性用于设置或返回元素的背景图像。

语法

以下是语法 −

设置 backgroundImage 属性:

object.style.backgroundImage = "url('URL')|none|initial|inherit"

值

以上属性值的解释如下 −

Sr.No值 &说明
1url('URL')
用于指定图像文件位置。
2none
用于指定不使用背景图像,这是默认值。
3initial
用于将此属性设置为 initial值。
4inherit
继承父级属性值。

示例

我们来看 backgroundImage 属性的示例 −

<!DOCTYPE html>
<html>
<head>
<style>
   #DIV1 {
      height: 300px;
      width: 500px;
      background-image: url("https://www.cainiaomax.com/mongodb/images/mongodb-minilogo.jpg");
      background-repeat: no-repeat;
      background-size: cover;
   }
</style>
<script>
   function changeBackImage(){
      document.getElementById("DIV1").style.backgroundImage="url('https://www.cainiaomax.com/plsql/images/plsql-mini-logo.jpg')";
      document.getElementById("Sample").innerHTML="The background image is now changed to PL/SQL Tutorial";
   }
</script>
</head>
<body>
<h2>Learn</h2>
<div id="DIV1"></div>
<p>Change the above div background image by clicking the below button</p>
<button onclick="changeBackImage()">CHANGE IMAGE</button>
<p id="Sample"></p>
</body>
</html>

输出

这将产生以下输出 −

点击"更改图片"按钮 −


相关文章


有用资源