1

我有一个 CSS 宽度和高度为 800x600 的 div 元素。我正在使用 javascript 在 div 中生成三个对象元素,它们应该在对角线上,相互接触。我正在使用 position:relative 以及 left 和 top 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但大黑色方块内的红色方块代替。有什么问题?

4

1 回答 1

0

position: fixed相对于视口定位元素。position: relative给出这个结果是因为objectelement 可能有一些默认值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.

于 2013-01-29T07:01:05.577 回答