获取类的outerHeight并取最大值

get outerHeight of class and take the biggest value

本文关键字:最大值 outerHeight 获取      更新时间:2023-09-26

我使用.outerHeight来设置另一个div的高度,使用一个类作为选择器。

var $example = $('.example');
var $height = $example.outerHeight();
var $styles = { 'height': $height }
$('.wrapper_sub').css($styles);

我想在我的网站的多个"幻灯片"上使用这个:

<div class="wrapper">
  <div class="example">Some Content</div>
  <div class="wrapper_sub">Other Content</div>
</div>
<div class="wrapper">
  <div class="example">Some Content</div>
  <div class="wrapper_sub">Other Content</div>
</div>
<div class="wrapper">
  <div class="example">Some Content</div>
  <div class="wrapper_sub">Other Content</div>
</div>

如何获取每个.example.outerHeight,只取最高值并将其附加到所有.wrapper_subdiv?

请参阅内联注释:

var maxHeight = 0; // Initialize to zero
var $example = $('.example'); // Cache to improve performance
$example.each(function() { // Loop over all the elements having class example
    // Get the max height of elements and save in maxHeight variable
    maxHeight = parseFloat($(this).outerHeight()) > maxHeight ? parseFloat($(this).outerHeight()) : maxHeight;
});
$('.wrapper_sub').height(maxHeight); // Set max height to all example elements

DEMO

循环遍历.example元素并获得最大值。然后将该值应用于这些元素:

//Set an empty array
var arr = [];
//Loop through the elements
$('.example').each(function() {
   //Push each value into the array
   arr.push(parseFloat($(this).outerHeight()));
});
//Get the max value with sort function
var maxH = arr.sort(function(a,b) { return b-a })[0];
//Apply the max value to the '.example' elements
$('.example').css({'height': maxH + 'px'});