1

私はcssの幅と高さ、800x600のdiv要素を持っています。私はjavascriptを使用して、互いに接触している対角線上にあるはずのdiv内の3つのオブジェクト要素を生成しています。私はposition:relativeと、leftおよびtopcssプロパティを使用してオブジェクト要素を配置しています。しかし、私がこのようにそれを行うとき、そこにあるべきではない正方形の間に水平方向のギャップがあります。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ビューポートを基準にして要素を配置します。element にはおそらく and のデフォルト値があるためposition: relative、その結果が得られます。次のようなものが必要です。objectwidhtheight

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 に答える