var elm = document.createElement("div");
elm.setAttribute("style","position:relative;top:40px;left:10px;width:170px;height:5px;background-color:#0099ff;");
var parent = document.getElementById("square");//id=square也是个div
parent.appendChild(elm);这样对应的HTML应该是<div id=parent>
    <div style="position:relative;top:40px;left:10px;width:170px;height:5px;background-color:#0099ff;">    </div>
</div>但是就是显示不出来,不知道哪里理解错了我改用以下方式var elm = document.createElement("div");
elm.innerHTML="<div style='position:relative;top:40px;left:10px;width:170px;height:5px;background-color:#0099ff;'/>"
var parent = document.getElementById("square");
parent.appendChild(elm);就可以了,他对应的HTML应该是<div id=square>
   <div>
        <div style='position:relative;top:40px;left:10px;width:170px;height:5px;background-color:#0099ff;>
        </div>
   </div>
</div>多了一层div,小弟不是很理解为什么这样就行,还有谁能解释下createElement到底创建的是什么?元素?对象? 标签?

解决方案 »

  1.   

    第一种
    elm.setAttribute换成elm.style.cssText= "position:relative;top:40px;left:10px;width:170px;height:5px;background-color:#0099ff;";
      

  2.   

    createElement创建的是DOM对象,<div>...</div>
      

  3.   

    在IE下面可以这么写的,在FF下貌似要分开写的。
    var elm = document.createElement("div");
    elm.setAttribute("style","position:relative;top:40px;");
    elm.setAttribute("style","width:170px;");
    elm.setAttribute("style","height:5px;");
    elm.setAttribute("style","background-color:#0099ff;");
    var parent = document.getElementById("square");//id=square也是个div
    parent.appendChild(elm);