开发者

How to manipulate width of multiple images in javascript

I have multiple images a开发者_如何学运维nd i wnat to place all of them in a single line.How should i manipulate the width of images such that the sum of width of al images does not exceed the browser's width.??


If you have variable width images you could go with something like this:


/**
*@param contId {string} id of the container element
*/
var imgResize = function(contId) {
    var imgs = [], totalWidth = 0, ratio = 0, containerWidth = 0;
    var cont = document.getElementById(contId);
    var child = cont.firstChild;
    while(child.nextSibling){
        if(child.tagName && child.tagName.toUpperCase() === 'IMG'){ 
            var imgW = child.clientWidth;
            imgs.push({node: child, width: imgW});
            totalWidth += imgW;
        }
        child = child.nextSibling;
    }
    ratio =  cont.clientWidth / totalWidth;

    imgs.forEach(function(img){
        var cWidth = Math.floor(ratio*img.width);
        img.node.style.cssText='width:'+cWidth+'px';
    });
};

/**
* Fire it on window resizes, ooohh shiny
*/
window.onresize=function(){imgResize('container');};

Keep in mind that you should probably do something like



img{border:0px;display:block;float:right;}
.imgContainer{font-size:0px;padding:0px;width:100%;/*for example*/}

Getting this to work in less than modern browsers is left as an exercise to the reader. And yes, using a framework is a fine idea, I would recommend YUI, so good that even Russians have been known to use it.


To be able to target them all at the same time give them all the same class or go from a containing id and get them by node name. After targeting them get their widths.

To get the widths into variables with jquery:

var $allImages = $('img.myImages');//all images need the same class

var allImagesW = $allImages.width() * $allImages.length;//you might want to use .outerWidth() to account for borders and padding, and .outerWidth(true) to include margins.

var windowW = $(window).width();


var width = (window.width / numImages) - margin;
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜