我遇到了jQuery代码的问题。
确实,我希望连续添加每个图像的每个宽度。所以我想它将通过jquery each()函数解决,但我不知道如何。
我已经知道如何获得一个图像的宽度,但我不能总计每个图像。
所以,我的第一步是选择我想要的每个图像。这很好,但现在每次尝试都失败了。 :(
images.each(function(i){
$(images).load(function(){
totalImageWidth = totalImageWidth + this.width;
});
});
请帮帮我。
提前致谢。
答案 0 :(得分:3)
var totalImageWidth = 0;
images.each(function(index, item){
totalImageWidth += item.width;
});
尝试使用item
(其中包含对单个图像的引用)
此代码假设它包含在$(function(){...})
中(等待在执行之前加载页面)。
答案 1 :(得分:1)
尝试以下方法:
var totalImagesWidth = 0;
$("img").each(function() {
totalImagesWidth += $(this).width();
});
alert(totalImagesWidth);
答案 2 :(得分:0)
我希望这会有所帮助....我用这个来创建一个类似于google play的移动网络应用程序,屏幕截图容器可滚动垂直。
这将是HTML:
<div id="img_container">
<img src="" />
<img src="" />
...
</div>
这是jQuery代码:
//use window.load to work with all browsers
//with document.ready its not working in chrome and safari
$(window).load(function() {
var img_width = 20; //start with a specific data, usually 0
$('#img_container').find('img').each(function() {
//for each img add the width plus a specific value, in this case 20
img_width += $(this).width() + 20;
});
//if you need the container to have the right width to fit all the images
$('#img_container').css('width', img_width);
});