Javascript制作的Div没有显示

时间:2014-03-17 23:37:18

标签: javascript html css

我有一个div(让我们称之为fatherDiv)具有相对位置和固定的宽度和高度。

我将此对象发送到javascript函数(init),该函数创建3个重叠的div并将它们作为fatherDiv的子项放置。然而,这三个重叠的div没有正确显示。

我希望得到这样的结果:

enter image description here

我正在尝试使用这些javascript函数来实现这一点:

   function fabDiv(width, z) {

    var element = document.createElement("div");
    element.setAttribute("height", "200px");
    element.setAttribute("width", width.toString()+"px");
    element.setAttribute("position", "absolute");
    element.setAttribute("top", "0");
    element.setAttribute("left", "0");
    element.setAttribute("z-index", z.toString());

    return element;
}
function init(container, /*img1, img2, img3,*/ interval) {

    div1 = fabDiv(294, 3);
    div2 = fabDiv(265, 2);
    div3 = fabDiv(235, 1);

    container.appendChild(div1);
    container.appendChild(div2);
    container.appendChild(div3);

    div3.setAttribute("background-color", "lightblue");
    div2.setAttribute("background-color", "blue");
    div1.setAttribute("background-color", "darkblue");
}

欢迎任何建议。谢谢:))

PS:当我使用Chrome上的F12来检查创建的html元素时,我可以看到代码中的div,但是小工具提示显示它们没有高度(0px)。

1 个答案:

答案 0 :(得分:1)

<强> DEMO

function fabDiv(width, bgCol) {  
    var el = document.createElement("div");  
    el.style.height = "200px";
    el.style.width = width+"px";
    el.style.position = "absolute";
    el.style.backgroundColor = bgCol;  
    return el;
}

function init(container, /*img1, img2, img3,*/ interval) {
    container.appendChild( fabDiv(294, "lightblue") );
    container.appendChild( fabDiv(265, "blue") );
    container.appendChild( fabDiv(235, "darkblue") );
}

var cont = document.getElementById('container');
init(cont);

另一种方法:

<强> DEMO

function CSS( el, prop, val ){
   if(!val && typeof prop == "object" ) for(var key in prop) el.style[key] = prop[key];
   else el.style[prop] = val;
   return el; 
}

function fabDiv( obj ) {
  var el = document.createElement("div");
  CSS(el, {height:"200px", width:obj.width+"px", position:"absolute", backgroundColor:obj.backgroundColor
  });
  document.getElementById(obj.appendTo).appendChild(el);
  return el;
}

function init() {
  fabDiv({width:294, backgroundColor:"lightblue", appendTo:'container'});
  fabDiv({width:265, backgroundColor:"blue", appendTo:'container'});
  fabDiv({width:235, backgroundColor:"darkblue", appendTo:'container'});
}
相关问题