使用JS循环创建的元素与另一个元素重叠

时间:2011-12-09 02:07:08

标签: javascript html css arrays function

我正在尝试将图片从div放到span。结果是图像重叠,我不知道如何在添加图像时定位每个图像。

这是我的代码:

CSS

<style type="text/css">
        body{background-image:url('image/wood.jpg');}
        h1, h3, h4, h5, h6, p{text-align:center; font-family:helvetica; font-weight:900;}
        h3, h4, h5 {color:red;}
        h1, h6, p{color:white;}
        img{height:120px;}
        span{display:inline-block; margin-left: 25px; height:250px;}
        div.inv{background-image:url('image/shelf.jpg'); background-position:fixed; 
            background-repeat:none;}
        span#la, span#me, span#sm{margin-left:auto; margin-right:auto; width:800px;}
        div{background-image:url('image/crate.jpg'); margin-left:25px; 
            margin-right:25px;}

Javascript

var temp = null;
        var largeArray = new Array(6);
function isTemp()
        {
            if(temp == null)
            {
                alert("Please pick an item to place in the container");
            }               
        }

function fillLarge()
        {
            isTemp();
            if(largeArray[0] != undefined &&largeArray[1] != undefined &&largeArray[2] != undefined && largeArray[3] != undefined &&largeArray[4] != undefined &&largeArray[5] != undefined)
            {
                alert('This crate is full');
            }
            else
            {
                for (var i=0; i<6; i++)
                {
                    if (largeArray[i] == undefined)
                    {
                        largeArray[i] = "<img src='image/"+temp+".jpg'/>";
                        document.getElementById("la").innerHTML = largeArray[i];
                        break;
                    }
                }
                document.getElementById(temp).style.display="none";
                temp = null;
            }
        }

HTML

<div>
    <h3> LARGE CONTAINER </h3>
    <span id="la" onclick="fillLarge();"> 
    </span> </div>
<span id = "gold" onclick = "temp = this.id;">
                <img src="image/gold.jpg"/>
                <p> Gold that you didn't farm </p>
            </span>
            <span id = "Moarg" onclick = "temp = this.id;">
                <img src="image/Moarg.jpg" />
                <p> Mo'arg Slave for <br /> your engineering needs </p>
            </span>
            <span id = "sweetroll" onclick = "temp = this.id;">
                <img src="image/sweetroll.jpg" />
                <p> Sweetroll stolen from a citizen </p>
            </span>
            <span id = "uranium" onclick = "temp = this.id;">
                <img src="image/uranium.jpg" />
                <p> Uranium Ore </p>
            </span>

我不知道如何使用jQuery,或者任何传递基本的javascript。

1 个答案:

答案 0 :(得分:2)

你的问题出在你的javascript中......

添加每个图像后,您将覆盖内部HTML而不是附加新图像。

更改...

document.getElementById("la").innerHTML = largeArray[i];

要...

document.getElementById("la").innerHTML += largeArray[i];

(注意&#34; + =&#34;附加新的html)