Chair's blog
2009年9月21日 星期一
createElement...等用法
createElement、setAttribute、insertBefore、appendChild 用法
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title></title> </head> <body> body innerHTML<br/> <script type="text/javascript"> //在 body innerHTML 前插入 div cElt=document.createElement("div"); cElt.setAttribute("id","divid"); cElt.innerHTML="I am DIV!"; var s=cElt.style; s.backgroundColor="black"; s.color="#FFF" s.MozOpacity=1; s.opacity=1; s.filter="alpha(opacity=100)"; //s.position="fixed"; s.top=0; s.left=0; s.width="100px"; s.height="100px"; s.zIndex=254; s.textAlign="left"; s.margin=0; s.padding=0; var a=document.getElementsByTagName("body").item(0); a.insertBefore(cElt,a.firstChild); //在 body innerHTML 插入 p pElt = document.createElement("p"); pElt.setAttribute("id", "pid"); pElt.innerHTML="I am P!"; s = pElt.style; s.padding = 0; s.margin = 0; s.fontFamily = "Arial, sans-serif"; s.fontSize = "14px"; s.textAlign = "left"; s.color = "#F00"; a.appendChild(pElt); </script> </body> </html>
appendChild、removeChild 用法
<!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> <title>Add/Remove child: Javascript</title> <script> function addEvent() { var ni = document.getElementById('myDiv'); var numi = document.getElementById('theValue'); var num = (document.getElementById("theValue").value -1)+ 2; numi.value = num; var divIdName = 'my'+num+'Div'; var newdiv = document.createElement('div'); newdiv.setAttribute('id',divIdName); newdiv.innerHTML = 'Element Number ' + num + ' has been added! <a href="javascript:void(0);" onclick="removeElement(\''+divIdName+'\')">Remove the element '+divIdName+'</a>'; ni.appendChild(newdiv); } function removeElement(divNum) { var d = document.getElementById('myDiv'); var olddiv = document.getElementById(divNum); d.removeChild(olddiv); } </script> </head> <body> <input type="hidden" value="0" id="theValue" /> <p><a href="javascript:void(0);" onclick="addEvent();">Add Some Elements</a></p> <div id="myDiv"> </div> </body> </html>
element 用法:
螞蟻的 JavaScript
沒有留言:
張貼留言
較新的文章
較舊的文章
首頁
訂閱:
張貼留言 (Atom)
沒有留言:
張貼留言