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

164 javascript

我如何使用JavaScript来创建和设置(并附加到页面)包含内容的div?我知道这是可能的,但是怎么样?

Igo*_*mov 262

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);
Run Code Online (Sandbox Code Playgroud)
<body>
<div id="main"></div>
</body>
Run Code Online (Sandbox Code Playgroud)

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);
Run Code Online (Sandbox Code Playgroud)

使用父引用而不是document.body.


jrh*_*ath 57

取决于你是如何做到的.纯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);
Run Code Online (Sandbox Code Playgroud)

使用jquery做同样的事情很容易:

$('body')
.append('my DOM manupulation skills dont seem like a big deal when using jquery')
.css('color', 'red').addClass('myclass');
Run Code Online (Sandbox Code Playgroud)

干杯!

  • 我不会说jQuery更容易,它大多只是更短.但是,我不使用setAttribute作为类,而是使用div.className ='myclass'; (4认同)
  • 一旦你开始开发繁重的javascript UI,jQuery就会变得更容易了.鉴于它从get go开始包含了编程的功能模型,它使您的代码看起来和行为也起作用.例证:ajax使用原生js vs jquery :) (4认同)
  • 调用jQuery"功能"是一个重要的延伸.你如何定义功能模型,你认为jQuery以什么方式拥抱它? (3认同)

小智 9

此解决方案使用jquery库

$('#elementId').append("<div class='classname'>content</div>");
Run Code Online (Sandbox Code Playgroud)

  • 有趣的看Javascript. (14认同)

Ran*_*eir 9

虽然这里的其他答案有效,但我注意到你要求一个包含内容的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);
Run Code Online (Sandbox Code Playgroud)

HTML:

<body>
  <h1>Title</h1>
  <p>This is a paragraph. Well, kind of.</p>
</body>
Run Code Online (Sandbox Code Playgroud)

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; }
Run Code Online (Sandbox Code Playgroud)

注意:CSS线从Ratal Tomal借来

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


小智 6

我喜欢做的另一件事是创建一个对象,然后循环访问该对象并设置样式,因为逐一编写每个样式可能很乏味。

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);
Run Code Online (Sandbox Code Playgroud)


小智 6

这将位于具有自定义 CSS 且类名为 Custom 的函数或脚本标记内

 var board = document.createElement('div');
 board.className = "Custom";
 board.innerHTML = "your data";
 console.log(count);
 document.getElementById('notification').appendChild(board);
Run Code Online (Sandbox Code Playgroud)


Pet*_*ter 5

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

var div = '<div id="yourId" class="yourClass" yourAttribute="yourAttributeValue">blah</div>';
Run Code Online (Sandbox Code Playgroud)

如果您希望属性和/或属性值基于变量:

var id = "hello";
var classAttr = "class";
var div = '<div id='+id+' '+classAttr+'="world" >Blah</div>';
Run Code Online (Sandbox Code Playgroud)

然后,附加到正文:

document.getElementsByTagName("body").innerHTML = div;
Run Code Online (Sandbox Code Playgroud)

非常简单。