最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jQuery each() image width - Stack Overflow

programmeradmin0浏览0评论

i've got a problem with a jQuery code.

Indeed i want to add each width of every image in a row. So i guess it will be solved with the jquery each() function but i dont know how.

I already know how i get one width of a image but i aint able to total each of them.

So, my first step is to select each image i want to. That works fine, but now every try failed. :(

images.each(function(i){
    $(images).load(function(){
        totalImageWidth = totalImageWidth + this.width;
    });
});

please help me.

Thanks in advance.

i've got a problem with a jQuery code.

Indeed i want to add each width of every image in a row. So i guess it will be solved with the jquery each() function but i dont know how.

I already know how i get one width of a image but i aint able to total each of them.

So, my first step is to select each image i want to. That works fine, but now every try failed. :(

images.each(function(i){
    $(images).load(function(){
        totalImageWidth = totalImageWidth + this.width;
    });
});

please help me.

Thanks in advance.

Share Improve this question asked Jun 7, 2011 at 15:08 YeppThat'sMeYeppThat'sMe 111 silver badge2 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 3
var totalImageWidth = 0;    
images.each(function(index, item){
    totalImageWidth += item.width;
});

Try that, using item (which has the reference to the individual image)

This code is under the assumption that it is wrapped in a $(function(){...}) (which waits for the page to be loaded before executing).

Try the following:

var totalImagesWidth = 0;
$("img").each(function() {
    totalImagesWidth += $(this).width();
});
alert(totalImagesWidth);

Demo: http://jsfiddle/pkCxL/

I hope this helps.... I used this to create a mobile web application similar to google play with the screenshot container scroll-able vertical.

This would be the HTML:

<div id="img_container">
    <img src="" />
    <img src="" />
    ...
</div>

and this is the jQuery code:

//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);
});
发布评论

评论列表(0)

  1. 暂无评论