我需要一个容器 div 作为其所有图像的组合宽度,加上最后一个图像的宽度。我已经得到了组合图像的宽度:
$(window).load(function() {
$('.pressimage').each(function() {
var totalImageWidth = 0;
$("img", this).each(function () {
totalImageWidth += $(this).width();
});
$(this).width(totalImageWidth);
});
});
那么我现在如何添加最后一张图像的宽度?我已经尝试过,但它不起作用:
$(window).load(function() {
$('.pressimage').each(function() {
var totalImageWidth = 0;
$("img", this).each(function () {
totalImageWidth += $(this).width();
});
$("img", this).last(function () {
lastImageWidth = $(this).width();
});
$(this).width(totalImageWidth + lastImageWidth);
});
});
谢谢
更新。 抱歉,我正在处理错误的代码。这是我所拥有的使 div 成为其所有图像的宽度的方法:
$(window).load(function() {
var pub_accum_width = 0;
$('.view-public-collection .pubimagecolor').find('img').each(function() {
pub_accum_width += $(this).width();
});
//alert(pub_accum_width);
$('.view-public-collection .view-content').width(pub_accum_width);
});
这是我修改后的代码,但它并没有使 div 更宽:
$(window).load(function() {
var pub_accum_width = 0;
var pub_accum_last = 0;
$('.view-public-collection .pubimagecolor').find('img').each(function() {
pub_accum_width += $(this).width();
});
$('.view-public-collection .pubimagecolor').find('img').last(function() {
pub_last_width += $(this).width();
});
$('.view-public-collection .view-content').width(pub_accum_width + pub_last_width);
});
谢谢
最佳答案
更新问题的答案:
$(window).load(function() {
var pub_accum_width = 0;
var pub_last_width = 0; // not pub_accum_last
$('.view-public-collection .pubimagecolor').find('img').each(function() {
pub_accum_width += $(this).width();
});
// ...last(function(...
$('.view-public-collection .pubimagecolor').find('img').last().each(function() {
pub_last_width += $(this).width();
});
$('.view-public-collection .view-content').width(pub_accum_width + pub_last_width);
});
last()
是一个单独的遍历函数,不能为其添加回调参数。选择最后一个元素,然后使用each()。您还使用不同的变量名称。
您必须在 last()
回调each()
回调之外定义 lastImageWidth
变量last()
,以便能够再次在外面使用它。
// ...
var totalImageWidth = 0;
var lastImageWidth = 0;
// ...
关于jquery - 所有包含元素的宽度 + 最后一个元素的宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4955559/