如何使用JavaScript创建和设置div样式?


Answers:


273

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


我知道这很老,但是添加类和相关的CSS将是更现代的方法,但这是一个不同的问题。
Mark Schultheiss

62

取决于您的操作方式。纯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');

干杯!


4
我不会说jQuery更容易,它只是更短。但是,不是使用setAttribute作为类,而是使用div.className ='myclass';。
威尔默

4
一旦开始开发沉重的javascript UI,jQuery就会变得非常容易。鉴于它从一开始就包含了编程的功能模型,因此它使您的代码也具有外观和行为功能。
恰当的例子

3
将jQuery称为“功能性”是一项主要工作。您如何定义功能模型,以及您认为jQuery接受它的方式如何?

如果您的应用程序中有10行,则jquery很棒。如果您使用它构建了一个认真的应用程序,欢迎来到地狱。
简短性不会

此处的jQuery部分未附加一个,div因此无法回答问题
Mark Schultheiss

10

虽然这里的其他答案有效,但我注意到您要求一个包含内容的div。所以这是我的版本,带有更多内容。JSFiddle链接位于底部。

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; }

注意:从Ratal Tomal借用的CSS行

JSFiddle: https ://jsfiddle.net/Rani_Kheir/erL7aowz/


9

此解决方案使用jquery库

$('#elementId').append("<div class='classname'>content</div>");

14
有趣的Javascript。
TheCarver '16

5

这是我要使用的一种解决方案:

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;

非常简单。


我应该在html页面上写些什么?
Nahiduzzaman女士罗斯(Rod)

1
我们需要在使用[0]时指定getElementsByTagName()。(太短,
无法

2

您可以这样创建

board.style.cssText = "position:fixed;height:100px;width:100px;background:#ddd;"

document.getElementById("main").appendChild(board);

完整的可运行代码段:

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>


2

用id名称创建div

var divCreator=function (id){
newElement=document.createElement("div");
newNode=document.body.appendChild(newElement);
newNode.setAttribute("id",id);
}

将文本添加到div

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

1

我喜欢做的另一件事是创建一个对象,然后循环遍历该对象并设置样式,因为这样可能会很麻烦,一个接一个地编写每个样式。

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);
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.