通过 JavaScript 中的函数设置 div 的背景图像
JavaScript 有多种方法可以使用图像源并将它们嵌入 HTML 正文中。
onclick
或 onchange
方法是用于更改 div
元素的函数。我们还可以在指向脚本行的 div
元素内创建一个 img
元素。
我们将执行两种设置 div
元素背景的方法。我们将在这两种情况下使用函数,不同之处在于创建一个 img
元素并在原始方法中设置背景。
在 JavaScript 中使用 HTML DOM style
属性设置 div
元素的背景
我们将首先在 HTML 结构中设置一个 div
元素,然后是一个名为 div
的 id
。
下面的控件转到我们的 button onclick
方法将触发功能 display
的脚本标签。
这里的 style
属性将在点击操作后操纵 DOM 设置背景图像。
代码片段:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Test</title>
</head>
<body>
<div id="Div" style="height:200px;width:200px;">
<button onclick="display()">Click</button>
</div>
<script>
function display(){
document.getElementById("Div").style.backgroundImage = 'url("https://pngimg.com/uploads/acorn/acorn_PNG37020.png")';
}
</script>
</body>
</html>
输出:
在 JavaScript 中使用 createElement
初始化 div
元素中的 img
元素以设置背景
在这种情况下,我们将在 HTML 结构中创建一个 div
元素,后跟一个 id
。
任务的其余部分生成一个对象,该对象将在脚本标签中保存图像 URL
。
稍后我们将获取 div id
并创建 img
元素。然后,图像对象将附加存储的 URL
并在 HTML 正文上预览。
代码片段:
<!DOCTYPE html>
<html>
<body>
<div id="imgDiv" style="height:200px;width:200px;"></div>
<script>
var pic = "https://pngimg.com/uploads/acorn/acorn_PNG37020.png";
function display(pic) {
let div = document.getElementById("imgDiv");
let img = document.createElement("img");
img.src = pic
div.append(img);
}
display(pic);
</script>
</body>
</html>
输出:
相关文章
Do you understand JavaScript closures?
发布时间:2025/02/21 浏览次数:108 分类:JavaScript
-
The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.
Do you know about the hidden traps in variables in JavaScript?
发布时间:2025/02/21 浏览次数:178 分类:JavaScript
-
Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av
How much do you know about the Prototype Chain?
发布时间:2025/02/21 浏览次数:150 分类:JavaScript
-
The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start
用 jQuery 检查复选框是否被选中
发布时间:2024/03/24 浏览次数:102 分类:JavaScript
-
在本教程中学习 jQuery 检查复选框是否被选中的所有很酷的方法。我们展示了使用直接 DOM 操作、提取 JavaScript 属性的 jQuery 方法以及使用 jQuery 选择器的不同方法。你还将找到许多有用的
jQuery 中的 Window.onload 与 $(document).ready
发布时间:2024/03/24 浏览次数:180 分类:JavaScript
-
本教程演示了如何在 jQuery 中使用 Window.onload 和 $(document).ready 事件。