我正在尝试使用 HTTP GET 请求拉取 Reddit 的首页,然后显示仅包含缩略图图像的网页。
到目前为止,这是我成功获取图像的 URL 和图像尺寸的代码。在我获得我需要的每个信息后,我试图创建一个新的 div 元素并将其附加到我通过 ID 获得的 gridArticle 元素。在这样做之前,我更新了它的类名以及图像和大小。
$.getJSON("https://www.reddit.com/.json", function (data) {
var items = [];
$.each(data.data.children, function (i, obj) {
if ((obj.data.preview != null) && (obj.data.preview.images != null)) {
var imageSourceUrl = preview.images[0].source.url;
var height = preview.images[0].source.height;
var width = preview.images[0].source.width;
var listingEntry = document.createElement("div");
listingEntry.className = "tile";
listingEntry.style.backgroundImage = "url(" + imageSourceUrl + ")";
listingEntry.style.width = width
listingEntry.style.height = height;
var gridArticle = document.getElementById("gridArticle");
gridArticle.appendChild(listingEntry);
}
});
});
HTML
<article id="gridArticle">
</article>
CSS
article .tile {
display: block;
float: left;
box-sizing: border-box;
font-size: 3em;
font-weight: 700;
padding: 0 6px;
color: #fff;
text-shadow: -1px 0 black, 0 1px black, 1px 0 black, 0 -1px black;
border:1px dotted black;
}
但是,如果我删除背景大小属性并在父文章 .tile{} 中添加高度和宽度属性并将它们设置为固定长度(例如 100 像素 100 像素),图像显示正常但只是在指定尺寸。
有什么想法吗?
最佳答案
您正在将图像添加到作为背景插入的 div 中。因此,它们的行为完全符合您的预期 - 如果 div 没有内容,那么它不会占用任何空间,因此您不会看到任何背景。设置背景尺寸不会影响 div 本身的尺寸。
解决方案:
- 在 JS 中获取现有的高度和宽度变量,并将它们应用为 CSS 高度和宽度。您无需费心设置背景大小;在 CSS 中将大小设置为“覆盖”。
- 在 div 上使用真实的图像元素而不是背景。
关于javascript - 使用 Javascript 将图像附加到自定义高度和宽度的 div 仅适用于设置尺寸,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34476844/