我如何使用 javascript 将图像插入到 div 中?

我有这个html代码


<!DOCTYPE html>

<html>

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Document</title>

    <link rel="stylesheet" href="tablezone.css">

    <script src="table.js"></script>  

</head>

<body> 

    <div id="divTable"; class="zone"></div>  

</body>

</html>

这是 JavaScript 代码:


var img = document.createElement("img");

img.src="/Tables/table.png";


var src = document.getElementById("divTable");

src.appendChild(img);

这是CSS代码:


body{

    background: url('/Tables/Riviera.jpeg');

    height: 100vh;

    background-size: cover;

    background-position: center;

    background-repeat: no-repeat;

}

.zone{

    background: rgba(200, 200, 200, 0.7);

    width: 1000px;

    height: 600px; 

    margin-left: 200px;  

}

当我在网络浏览器上运行代码时,显示的 div 中没有图像。


梵蒂冈之花
浏览 58回答 1
1回答

MMMHUHU

该脚本在divTable添加到 DOM 之前运行,因此该行document.getElementById("divTable")返回null。将标签移动script到主体的末尾可确保该divTable元素在运行之前位于 DOM 中getElementById。<!DOCTYPE html><html><head>&nbsp; &nbsp; <meta charset="UTF-8">&nbsp; &nbsp; <meta name="viewport" content="width=device-width, initial-scale=1.0">&nbsp; &nbsp; <title>Document</title>&nbsp; &nbsp; <link rel="stylesheet" href="tablezone.css"></head><body>&nbsp;&nbsp; &nbsp; <div id="divTable" class="zone"></div>&nbsp;&nbsp; &nbsp; <script src="table.js"></script>&nbsp;</body></html>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Html5