简体   繁体   中英

How to get max width of a set of divs based on their class?

I am trying to figure out a JavaScript function that upon an event (like 'onchange'). Will chack the width of all div with a certain class, select the max and set the width of that class to that max. I know how to do the second part but I have a problem with identifying the max width for a class. The divs of the same class are located in diffrent parent divs and their id's are incremented like: div1, div2, div3 ... if that helps at all. I know there are a couple of very similar questions here but I could not find the answer to when it's to be based on class AND when the divs are located in DIFFERENT parent divs. Thank you

Here we go

 $("button").click(function(){ $(".dad div").css("width",$(".dad div").css("max-width")); }); 
 .dad { display: table; border: 1px solid black; height: 100px; max-width: 10000px; width: 100px; } .dad div { display: table; border: 1px solid black; height: 100px; max-width: 10000px; width: 100px; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button>MAX WIDTH!</button> <div class="dad"> <div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div> </div> 

You can use below function to get max width among all divs

function getMaxWidth() {
    max = 0;
    $("div .image").each(function(){
        c_width = parseInt($(this).width());
        if (c_width > max) {
            max = c_width;
        }
    });
    return max;
}

working fiddle

You get all divs with a certain class by running document.getElementsByClassName(className) , it doesn't matter if the divs with className have different parent elements.

You can get the width of each div with the getBoundingClientRect() method, here's how you can map it to an array:

var widths = [].slice.call(document.getElementsByClassName(className))
  .map(function(div){ return div.getBoundingClientRect().width; });

And then you can get the maximum value with Math.max() :

var maxWidth = Math.max.apply(null, widths);

And there you have it!

You can run this script on onchange

 document.getElementsByClassName('some-class');
 var id = null;
 var maxw = 0; 
 for(var i=0;i<x.length;i++){
    if(x[i].clientWidth > maxw){
       maxw = x[i].clientWidth;
       id = x[i].id
    }
 }

id will have the id of the element with the maximum width and maxw will have the max with for that class and after that you can give that width to all the elements with that class. The solution will not be dependent on jQuery anymore.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM