子元素位置相对工作错误

Child element position relative working wrong

本文关键字:工作 错误 相对 位置 元素      更新时间:2023-09-26

我有一个 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);

这就是我得到的:链接1

这就是我想要的:Link2 但大黑方块内的红色方块。怎么了?

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