开发者

jQuery each() image width

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.


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.net/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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜