如何使用JavaScript创建和样式化一个div?

211

如何使用JavaScript创建、设置样式并将一个div追加到页面上? 我知道这是可能的,但怎么做呢?


请参见https://dev59.com/oW025IYBdhLWcg3wkW4F。 - Cees Timmerman
12个回答

0
如果有人想知道的话,这也可以用一行代码实现。
document.body.appendChild(Object.assign(document.createElement("div"), { "style": "background-color:red;color:white", "className": "myClass", "innerText": "Helloo" }))

Jsfiddle


-2
你可以直接使用下面的方法:
document.write()

非常简单,在下面的文档中我会解释

document.write("<div class='div'>Some content inside the div (It is styled!)</div>")
.div {
  background-color: red;
  padding: 5px;
  color: #fff;
  font-family: Arial;
  cursor: pointer;
}

.div:hover {
  background-color: blue;
  padding: 10px;
}

.div:hover:before {
  content: 'Hover! ';
}

.div:active {
  background-color: green;
  padding: 15px;
}

.div:active:after {
  content: ' Active! or clicked...';
}
<p>Below or above well show the div</p>
<p>Try pointing hover it and clicking on it. Those are tha styles aplayed. The text and background color changes.</p>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接