gpt4 book ai didi

javascript - 动态创建元素的绝对定位

转载 作者:行者123 更新时间:2023-11-30 12:40:28 25 4
gpt4 key购买 nike

我正在尝试将文本叠加到使用 document.createElement() 函数动态创建的超链接图像上。然而,即使绝对位置为 left: 0pxtop: 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/

block 和内联 block 不起作用: http://jsfiddle.net/MwjXV/

最佳答案

第一个解决方案

// 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

关于javascript - 动态创建元素的绝对定位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24659648/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com