[英]How to Add Element Created in JavaScript File to HTML page
I am attempting a create an element in the js file which will then be added to the html div where the game is我正在尝试在 js 文件中创建一个元素,然后将其添加到游戏所在的 html div
I am trying to make a createMine function that creates a new element with the style in.mine and then adds it the the html game div.我正在尝试创建一个 createMine function,它创建一个具有 in.mine 样式的新元素,然后将其添加到 html 游戏 div。
var newMine = document.createElement("div"); newMine.classList.add(".mine"); document.getElementById("game").appendChild(newMine);
.mine { width: 20px; height: 20px; background-color: blue; position: relative; display: inline; }
<div id="game"> <button id="startButton">Click To Start</button> <div id="gameElements"> <div id="character"> </div> </div> </div>
Your code is working properly except two problems:您的代码工作正常,除了两个问题:
newMine.classList.add(".mine");
should be newMine.classList.add("mine");
应该是
newMine.classList.add("mine");
(don't use the .
when adding the class, its only purpose is to tell CSS that the following is a CSS class). (在添加 class 时不要使用
.
,其唯一目的是告诉 CSS 以下是 CSS 类)。
Elements that have display: inline
don't accept height
or width
.具有
display: inline
的元素不接受height
或width
。 Use display: inline-block
instead.使用
display: inline-block
代替。
var newMine = document.createElement("div"); newMine.classList.add("mine"); document.getElementById("game").appendChild(newMine);
.mine{ width: 20px; height: 20px; background-color: blue; position: relative; display: inline-block; }
<div id="game"> <button id="startButton">Click To Start</button> <div id="gameElements"> <div id="character"></div> </div> </div>
when using classlist, don't write a dot at the beginning to make it work it works.使用 classlist 时,不要在开头写一个点以使其正常工作。 and as @connexo said, use inline-block
正如@connexo 所说,使用 inline-block
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.