我如何使用 JavaScript 来创建和设置样式(并附加到页面)一个带有内容的 div?我知道这是可能的,但怎么做?
如何使用 JavaScript 创建 div 并为其设置样式?
IT技术
javascript
2021-01-22 14:34:27
6个回答
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
.
取决于你是如何做的。纯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。所以这是我的带有额外内容的版本。底部的 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/
此解决方案使用 jquery 库
$('#elementId').append("<div class='classname'>content</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;
易如反掌。