我如何使用JavaScript创建和风格(并追加到页面)一个div,与内容? 我知道这是可能的,但怎么做呢?
当前回答
var div = document.createElement("div"); Div.style.width = "100px"; Div.style.height = "100px"; Div.style.background = "red"; Div.style.color = "白色"; div.innerHTML = "Hello"; . getelementbyid(“主要”).appendChild (div); 身体< > < div id = "主" > < / div > 身体< / >
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。
其他回答
你可以使用下面的方法:
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>
虽然其他答案在这里工作,我注意到您要求一个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; }
注意:CSS线条借用Ratal Tomal
JSFiddle: https://jsfiddle.net/Rani_Kheir/erL7aowz/
下面是一个小例子,它使用了一些漂亮的可重用DOM实用函数:
// DOM utility functions: const ELNew = (tag, prop) => Object.assign(document.createElement(tag), prop), ELS = (sel, par) => (par ?? document).querySelectorAll(sel), EL = (sel, par) => (par ?? document).querySelector(sel); // Task: const EL_new = ELNew("div", { className: "item", textContent: "Hello, World!", onclick() { console.log(this.textContent); }, style: ` font-size: 2em; color: brown; background: gold; ` }); // Append it EL("body").append(EL_new);
此外,你还可以使用Object.assign()对元素进行样式化,如下所示:
// Add additional styles later:
Object.assign(EL_new.style, {
color: "red",
background: "yellow",
fontSize: "3rem",
});
这里有一个我会使用的解决方案:
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;
容易得很。
这取决于你怎么做。纯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');
干杯!
推荐文章
- JavaScript: override alert()
- 重置setTimeout
- 如何确保<select>表单字段被禁用时提交?
- jQuery有不聚焦的方法吗?
- 反应钩子-正确的方式清除超时和间隔
- TypeScript枚举对象数组
- 在React.js中正确的img路径
- 在React.js中更新组件onScroll的样式
- onClick ReactJS调用多个函数
- 如何在JavaScript中转义单引号(')?
- Ng-repeat结束事件
- 谷歌MAP API未捕获的类型错误:无法读取属性“offsetWidth”为空
- 模糊vs聚焦-有什么真正的区别吗?
- 如何使用JavaScript创建和样式一个div ?
- 清除JavaScript中的缓存