动态创建元素的绝对定位

时间:2014-07-09 17:00:17

标签: javascript html dom

我正在尝试将文本叠加到使用 document.createElement()函数动态创建的超链接图像上。但是,即使 left的绝对位置:0px top:0px ,文本仍然会出现在图像下方,而不是应该位于左上角:

    //mainDiv is a container to hold all the hyperlinked images
    for (i = 0; i < imgArray.length; i++)
    {
        img = document.createElement("img");
        img.src = imgArray[i].src;
        img.style.width = imgArray[i].wdth;
        img.style.height = "auto";

        imgLink = document.createElement("a");
        imgLink.href = imgArray[i].url;
        imgLink.appendChild(img);

        imgLabel = document.createElement("p");
        imgLabel.innerHTML = imgArray[i].desc;
        imgLabel.style.position = "absolute";
        imgLabel.style.top = "0px";
        imgLabel.style.left = "0px";

        imgContainer = document.createElement("div");
        imgContainer.style.display = "inline";
        imgContainer.style.position = "relative";

        imgContainer.appendChild(imgLabel);
        imgContainer.appendChild(imgLink);
        mainDiv.appendChild(imgContainer);
    }

唯一的问题是文本div的定位, imgLabel

以下是jsFiddle问题的简化示例: http://jsfiddle.net/mPL3q/1/

阻止&amp;内联块不起作用: http://jsfiddle.net/MwjXV/

2 个答案:

答案 0 :(得分:2)

第一个解决方案

// label
imgLabel.style.position = "absolute";
imgLabel.style.top = "0px";
imgLabel.style.left = "0px";
imgLabel.style.margin = '0px';

// container    
imgContainer.style.position = "relative";
// tip: parent element of another element containing floated elements 
//      should have property overflow set to hidden
imgContainer.style.float = "left";
imgContainer.style.margin = "5px";

第二个解决方案

// label
imgLabel.style.position = "absolute";
imgLabel.style.top = "0px";
imgLabel.style.left = "0px";
imgLabel.style.margin = "0px";

// container        
imgContainer.style.display = "inline-block";
imgContainer.style.position = "relative";
// you will have gaps between the containers even if the margin is set to 0
imgContainer.style.margin = "0px";
// if you don't want these gaps, set margin-left to -5px (but not to the first element)
if(i !== 0){
    imgContainer.style.marginLeft = "-5px";
}

EDIT分析您的代码后......

// change <p> to <label>
imgLabel = document.createElement("label");
imgLabel.innerHTML = "Image " + i;
imgLabel.style.left = "0px";
// you don't need the next line ;)
//imgLabel.style.top = "0px";
imgLabel.style.color = "White";
imgLabel.style.position = "absolute";

1st jsFiddle | 2nd jsFiddle | 3rd jsFiddle

答案 1 :(得分:1)

你可以这样做,添加

img.style.zIndex="1";

imgLink.style.display = "block";

到他们各自的街区

http://jsfiddle.net/mPL3q/8/

OR

如果inline-block适用于您,那么

imgContainer.style.display = "inline-block";

http://jsfiddle.net/mPL3q/7/