原生JS创建DIV.


Javascript代码:

[javascript]  view plain  copy
  1. function create(){  
  2.     //创建一个div  
  3.     var div = document.createElement("div");  
  4.       
  5.     //为div创建属性class = "test"  
  6.     var divattr = document.createAttribute("class");  
  7.     divattr.value = "test";  
  8.       
  9.     //把属性class = "test"添加到div  
  10.     div.setAttributeNode(divattr);  
  11.       
  12.     //创建一个值为test的按钮  
  13.     var input = document.createElement("input");  
  14.     var inputattr = document.createAttribute("type");  
  15.     inputattr.value = "button";  
  16.     input.setAttributeNode(inputattr);  
  17.     var inputattr1 = document.createAttribute("value");  
  18.     inputattr1.value = "test";  
  19.     input.setAttributeNode(inputattr1);  
  20.       
  21.     //创建一hello,world个文本节点  
  22.     var text = document.createTextNode("hello,world");  
  23.       
  24.     //将按钮和文本节点追加到div  
  25.     div.appendChild(input);  
  26.     div.appendChild(text);  
  27.       
  28.     //为div添加样式  
  29.     var style = document.createAttribute("style");  
  30.     div.setAttributeNode(style);  
  31.     div.style.backgroundColor = "#F00";  
  32.     div.style.borderWidth = "20px";  
  33.     div.style.borderColor = "#000";  
  34.     div.style.width = "500px";  
  35.     div.style.height = "500px";  
  36.     div.style.marginLeft = "30%";  
  37.     div.style.marginTop = "1%";  
  38.       
  39.     //把div追加到body  
  40.     document.getElementsByTagName("body").item(0).appendChild(div);  
  41. }  


HTML代码:

[html]  view plain  copy
  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
  2. <html xmlns="http://www.w3.org/1999/xhtml">  
  3. <head>  
  4. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />  
  5. <title>无标题文档</title>  
  6. <script type="text/javascript" src="test.js"></script>  
  7. </head>  
  8.   
  9. <body>  
  10.   
  11. <input type="button" onclick="create()" value="按钮" />  
  12.   
  13. </body>  
  14. </html>  


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

华洛

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值