How to manipulate the width of multiple images in javascript

I have several images and I have to put them all on one line. How should I manipulate the width of the images so that the sum of the width of the al-images does not exceed the width of the browser.

+3
source share
3 answers

If you have variable width images, you can go 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 modern browsers remains as an exercise for the reader. And yes, using the framework is a great idea, I would recommend YUI, so good that even the Russians, as you know, used it.

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

To be able to target them, you give them all the same classes at the same time or go from the one containing the identifier and get them under the name node. After they are targeted, they get the width.

To get the width in variables using 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();
0
source

Source: https://habr.com/ru/post/1749140/


All Articles