我如何使用JavaScript创建和风格(并追加到页面)一个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 > 身体< / >
其他回答
这个解决方案使用jquery库
$('#elementId').append("<div class='classname'>content</div>");
创建id为name的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
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>
你可以这样做
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 > 身体< / >
推荐文章
- 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中的缓存