我有一个 js 文件,它执行 ajax 发布并从 URL 获取图像。
图像被添加到 500x500 (px) 的 div。
我想为从 ajax post 返回的每张图片设置不同的大小...
我想使用 6 种不同的图像尺寸。
所以我想要实现的是让 1、7、13 号图片具有相同的大小
图2、8、14大小相同……等
$.post(URL, function (data) {
var container = $("#container");
container.html("");
$.each(data, function () {
var thumb = $("<div>");
var image = $("<img>").attr("src", this.ImageUrl);
var title = $("<span>").html(this.Title);
thumb.append(title);
// each picture will be faded in after 3.5 seconds
thumb.append(image).fadeIn(3500);
container.append(thumb);
});
});
最佳答案
我认为这样的事情可能会奏效:
//create an array with all the different sizes (widths and heights)
var sizes = [[100,100], [200,200],[300,300],[400,400],[500,500],[600,600]];
$.post(URL, function (data) {
var container = $("#container");
container.html("");
$.each(data, function (i) {
var thumb = $("<div>");
var image = $("<img>").attr("src", this.ImageUrl);
var title = $("<span>").html(this.Title);
//get the loop number and find the right image size in the array
image.attr("width", sizes[i % sizes.length][0]);
image.attr("height", sizes[i % sizes.length][1]);
thumb.append(title);
// each picture will be faded in after 3.5 seconds
thumb.append(image).fadeIn(3500);
container.append(thumb);
});
});
我在这里写了一个演示:http://jsfiddle.net/qfpdgpfo/1/ 注意:我删除了演示中的整个 ajax 部分,因为我没有要发布到的 url,但代码应该是相同的:
演示代码:
//method 1
$(".method1 img").each(function(i) {
$(this).attr("width", sizes[i % sizes.length][0]);
$(this).attr("height", sizes[i % sizes.length][1]);
});
//method2
$(".method2 img").each(function(i) {
$(this).css({"width": sizes[i % sizes.length][0], "height":sizes[i % sizes.length][1]});
})
//method3
$(".method3 img").each(function(i) {
$(this).addClass("size-" + i % sizes.length)
})
关于javascript - jQuery:在来自ajax post的图像上设置不同的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28317213/