我如何使用JavaScript创建和风格(并追加到页面)一个div,与内容? 我知道这是可能的,但怎么做呢?


当前回答

这里有一个我会使用的解决方案:

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;

容易得很。

其他回答

你可以使用下面的方法:

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>

这个解决方案使用jquery库

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

你可以这样做

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

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

完整的可运行代码片段: var董事会; 董事会= document.createElement (" div "); 董事会。id = "主板"; board.style.cssText = "位置:固定;高度:100px;宽度:100px;背景:#ddd;" . getelementbyid(“主要”).appendChild(板); 身体< > < div id = "主" > < / 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);

这取决于你怎么做。纯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');

干杯!