如何使用 JavaScript 创建 div 并为其设置样式?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6840326/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I create and style a div using JavaScript?
提问by Igor Dymov
How can I use JavaScript to create and style (and append to the page) a div, with content? I know it's possible, but how?
我如何使用 JavaScript 来创建和设置样式(并附加到页面)带有内容的 div?我知道这是可能的,但怎么做?
回答by Igor Dymov
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);
Use parent reference instead of document.body
.
使用父引用而不是document.body
.
回答by jrharshath
Depends on how you're doing it. Pure javascript:
取决于你是如何做的。纯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);
Doing the same using jquery is embarrassingly easy:
使用 jquery 做同样的事情非常容易:
$('body')
.append('my DOM manupulation skills dont seem like a big deal when using jquery')
.css('color', 'red').addClass('myclass');
Cheers!
干杯!
回答by Rani Kheir
While other answers here work, I notice you asked for a div with content. So here's my version with extra content. JSFiddle link at the bottom.
虽然这里的其他答案有效,但我注意到您要求一个包含内容的 div。所以这是我的带有额外内容的版本。底部的 JSFiddle 链接。
JavaScript(with comments):
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:
HTML:
<body>
<h1>Title</h1>
<p>This is a paragraph. Well, kind of.</p>
</body>
CSS:
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; }
Note: CSS lines borrowed from Ratal Tomal
注意:从 Ratal Tomal 借用的 CSS 行
JSFiddle:https://jsfiddle.net/Rani_Kheir/erL7aowz/
JSFiddle:https ://jsfiddle.net/Rani_Kheir/erL7aowz/
回答by banners
this solution uses the jquery library
此解决方案使用 jquery 库
$('#elementId').append("<div class='classname'>content</div>");
回答by Peter
Here's one solution that I'd use:
这是我会使用的一种解决方案:
var div = '<div id="yourId" class="yourClass" yourAttribute="yourAttributeValue">blah</div>';
If you wanted the attribute and/or attribute values to be based on variables:
如果您希望属性和/或属性值基于变量:
var id = "hello";
var classAttr = "class";
var div = '<div id='+id+' '+classAttr+'="world" >Blah</div>';
Then, to append to the body:
然后,附加到正文:
document.getElementsByTagName("body").innerHTML = div;
Easy as pie.
非常简单。
回答by Mahesh K
You can create like this
你可以这样创建
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>
回答by wly185
create div with id name
创建带有 id 名称的 div
var divCreator=function (id){
newElement=document.createElement("div");
newNode=document.body.appendChild(newElement);
newNode.setAttribute("id",id);
}
add text to div
将文本添加到 div
var textAdder = function(id, text) {
target = document.getElementById(id)
target.appendChild(document.createTextNode(text));
}
test code
测试代码
divCreator("div1");
textAdder("div1", "this is paragraph 1");
output
输出
this is paragraph 1
回答by Kenneth
Another thing I like to do is creating an object and then looping thru the object and setting the styles like that because it can be tedious writing every single style one by one.
我喜欢做的另一件事是创建一个对象,然后循环遍历该对象并设置这样的样式,因为逐个编写每个样式可能很乏味。
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);