![](/img/trans.png)
[英]How to add text to HTML element on web page using JavaScript DOM
[英]How to Add Element Created in JavaScript File to HTML page
我正在嘗試在 js 文件中創建一個元素,然后將其添加到游戲所在的 html 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>
您的代碼工作正常,除了兩個問題:
newMine.classList.add(".mine");
應該是newMine.classList.add("mine");
(在添加 class 時不要使用.
,其唯一目的是告訴 CSS 以下是 CSS 類)。
具有display: inline
的元素不接受height
或width
。 使用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>
使用 classlist 時,不要在開頭寫一個點以使其正常工作。 正如@connexo 所說,使用 inline-block
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.