如何使用JavaScript创建、设置样式并将一个div追加到页面上? 我知道这是可能的,但怎么做呢?
如何使用JavaScript创建、设置样式并将一个div追加到页面上? 我知道这是可能的,但怎么做呢?
var div = document.createElement("div");
div.style.width = "100px";
div.style.height = "100px";
div.style.background = "red";
div.style.color = "white";
div.innerHTML = "Hello";
document.getElementById("main").appendChild(div);
<body>
<div id="main"></div>
</body>
var div = document.createElement("div");
div.style.width = "100px";
div.style.height = "100px";
div.style.background = "red";
div.style.color = "white";
div.innerHTML = "Hello";
document.getElementById("main").appendChild(div);
OR
document.body.appendChild(div);
使用父引用代替 document.body
。
const width = 100
,我必须写成 el.style.width = \
${width}px`而不是仅仅写成
el.style.width = width`。 - Gustavo Straube这取决于你是如何做的。如果是纯javascript:
var div = document.createElement('div');
div.innerHTML = "my <b>new</b> skill - <large>DOM maniuplation!</large>";
// set style
div.style.color = 'red';
// better to use CSS though - just set class
div.setAttribute('class', 'myclass'); // and make sure myclass has some styles in css
document.body.appendChild(div);
使用jQuery做同样的事情非常容易:
$('body')
.append('my DOM manupulation skills dont seem like a big deal when using jquery')
.css('color', 'red').addClass('myclass');
祝福!
div
,因此无法回答问题。 - Mark Schultheiss其他回答已经有效,但我注意到你需要一个有内容的
JavaScript (带注释):
// Creating a div element
var divElement = document.createElement("Div");
divElement.id = "divID";
// Styling it
divElement.style.textAlign = "center";
divElement.style.fontWeight = "bold";
divElement.style.fontSize = "smaller";
divElement.style.paddingTop = "15px";
// Adding a paragraph to it
var paragraph = document.createElement("P");
var text = document.createTextNode("Another paragraph, yay! This one will be styled different from the rest since we styled the DIV we specifically created.");
paragraph.appendChild(text);
divElement.appendChild(paragraph);
// Adding a button, cause why not!
var button = document.createElement("Button");
var textForButton = document.createTextNode("Release the alert");
button.appendChild(textForButton);
button.addEventListener("click", function(){
alert("Hi!");
});
divElement.appendChild(button);
// Appending the div element to body
document.getElementsByTagName("body")[0].appendChild(divElement);
HTML:
<body>
<h1>Title</h1>
<p>This is a paragraph. Well, kind of.</p>
</body>
CSS:
h1 { color: #333333; font-family: 'Bitter', serif; font-size: 50px; font-weight: normal; line-height: 54px; margin: 0 0 54px; }
p { color: #333333; font-family: Georgia, serif; font-size: 18px; line-height: 28px; margin: 0 0 28px; }
注意:CSS样式取自Ratal Tomal
此解决方案使用jQuery库。
$('#elementId').append("<div class='classname'>content</div>");
我喜欢做的另一件事是创建一个对象,然后通过循环遍历该对象并设置样式,因为逐个编写每个样式可能会很繁琐。
var bookStyles = {
color: "red",
backgroundColor: "blue",
height: "300px",
width: "200px"
};
let div = document.createElement("div");
for (let style in bookStyles) {
div.style[style] = bookStyles[style];
}
body.appendChild(div);
var board = document.createElement('div');
board.className = "Custom";
board.innerHTML = "your data";
console.log(count);
document.getElementById('notification').appendChild(board);
以下是我会使用的一个解决方案:
var div = '<div id="yourId" class="yourClass" yourAttribute="yourAttributeValue">blah</div>';
var id = "hello";
var classAttr = "class";
var div = '<div id='+id+' '+classAttr+'="world" >Blah</div>';
document.getElementsByTagName("body").innerHTML = div;
易如反掌。
getElementsByTagName()
时,我们需要指定 [0]
。 - HKJeffervar divCreator=function (id){
newElement=document.createElement("div");
newNode=document.body.appendChild(newElement);
newNode.setAttribute("id",id);
}
var textAdder = function(id, text) {
target = document.getElementById(id)
target.appendChild(document.createTextNode(text));
}
测试代码
divCreator("div1");
textAdder("div1", "this is paragraph 1");
输出
this is paragraph 1
board.style.cssText = "position:fixed;height:100px;width:100px;background:#ddd;"
document.getElementById("main").appendChild(board);
Complete Runnable Snippet:
var board;
board= document.createElement("div");
board.id = "mainBoard";
board.style.cssText = "position:fixed;height:100px;width:100px;background:#ddd;"
document.getElementById("main").appendChild(board);
<body>
<div id="main"></div>
</body>
这里是一个小例子,它使用了一些巧妙的可复用的DOM实用函数:
// DOM utility functions:
const
elNew = (tag, prop) => Object.assign(document.createElement(tag), prop),
els = (sel, par) => (par ?? document).querySelectorAll(sel),
el = (sel, par) => (par ?? document).querySelector(sel);
// Task:
const elItem = elNew("div", {
className: "item",
textContent: "Hello, World!",
onclick() {
console.log(this.textContent);
},
style: `
font-size: 2em;
color: brown;
background: gold;
`
});
// Append it
el("body").append(elItem);
此外,您还可以使用Object.assign()为元素添加样式,例如:
// Utility functions
const css = (el, styles) => Object.assign(el.style, styles);
// Example:
css(elItem, { color: "blue", padding: "1rem" });