原生js创建一个div层
2016-04-01 09:34
627 查看
原生js创建一个div层
Javascript代码:
HTML代码:
Javascript代码:
function create(){ //创建一个div var div = document.createElement("div"); //为div创建属性class = "test" var divattr = document.createAttribute("class"); divattr.value = "test"; //把属性class = "test"添加到div div.setAttributeNode(divattr); //创建一个值为test的按钮 var input = document.createElement("input"); var inputattr = document.createAttribute("type"); inputattr.value = "button"; input.setAttributeNode(inputattr); var inputattr1 = document.createAttribute("value"); inputattr1.value = "test"; input.setAttributeNode(inputattr1); //创建一hello,world个文本节点 var text = document.createTextNode("hello,world"); //将按钮和文本节点追加到div div.appendChild(input); div.appendChild(text); //为div添加样式 var style = document.createAttribute("style"); div.setAttributeNode(style); div.style.backgroundColor = "#F00"; div.style.borderWidth = "20px"; div.style.borderColor = "#000"; div.style.width = "500px"; div.style.height = "500px"; div.style.marginLeft = "30%"; div.style.marginTop = "1%"; //把div追加到body document.getElementsByTagName("body").item(0).appendChild(div); }
HTML代码:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>无标题文档</title> <script type="text/javascript" src="test.js"></script> </head> <body> <input type="button" onclick="create()" value="按钮" /> </body> </html>
相关文章推荐
- JS中多步骤多分步的StepJump组件实例详解
- JS判断对象是不是数组“Array”
- js获取项目路径
- JSON练习
- js+flash实现的5图变换效果广告代码(附演示与demo源码下载)
- HTML5培训第二节课笔记(事件,原型,JSON)
- js中字符串编码函数escape()、encodeURI()、encodeURIComponent()区别详解
- js实现继承
- split()函数,join()函数,splice()函数的学习与总结
- JS回调函数
- json数据与html模版的转换
- js学习笔记(四)
- javascript(js)对子窗口和父窗口的一些操作方法
- Js三种弹框方式
- javascript call
- JavaScript语言精粹笔记
- 通过JS操作iframe中的内容,遇到的问题
- js中==和===的区别
- javascript 闭包理解例子
- js 双对象法则