子元素位置相对工作错误

时间:2013-01-29 06:39:22

标签: javascript html css position

我有一个css宽度和高度的div元素,800x600。我使用javascript在div中生成三个对象元素,它们应该在对角线上,相互接触。我使用position:relative,以及左侧和顶部css属性来定位对象元素。但是,当我这样做的时候,不应该存在的方块之间存在水平间隙。当我使用positon:fixed时,它们排列我想要的但不在div元素内。

我的div元素的HTML

<div id="Stage" style="background:black;width:800px;height:600px;margin-left:auto;margin-right:auto;overflow:hidden;">

和我的javascript

w="w";
level_data =
[
[w,0,0],
[0,w,0],
[0,0,w],
];

function generate(level_data){
    for(row=0;row<level_data.length;row++){
        for(col=0;col<level_data[row].length;col++){
            posx = col*50; posy=row*50;
            if(level_data[row][col]=="w"){
                entity = document.createElement('object');
                entity.style.position = "relative";
                entity.style.left = String(posx)+"px"; entity.style.top = String(posy)+"px";
                entity.data = "Objects/Sprites/Wall.jpg";
                document.getElementById("Stage").appendChild(entity);

            }
        }
    }
}
generate(level_data);

这就是我得到的:Link1

这就是我想要的:Link2但是大黑方块内的红色方块代替。有什么问题?

1 个答案:

答案 0 :(得分:0)

position: fixed定位相对于视口的元素。 position: relative会给出结果,因为object元素可能包含widhtheight的默认值。你需要这样的东西:

entity.style.position = "absolute";
entity.style.left = String(posx)+"px";
entity.style.top = String(posy)+"px";
entity.style.width = "50px";
entity.style.height = "50px";

使用position: absolute时,即使没有entity的维度,代码也可以正常工作。请注意,使用position: relative时,您不应将位置值与col相乘,它们应该只是50px