요소 집합에서 최대 높이를 가진 요소


85

div요소 집합이 있습니다. 에서는 jQuery, 나는을 찾을 수 있도록하고 싶습니다 div최대 높이와 또한의 높이 div. 예를 들면 :

<div>
    <div class="panel">
      Line 1
      Line 2
    </div>
    <div class="panel">
      Line 1<br/>
      Line 2<br/>
      Line 3<br/>
      Line 4<br/>
    </div>
    <div class="panel">
      Line 1
    </div>
    <div class="panel">
      Line 1
      Line 2
    </div>
</div>

위의 내용을 살펴보면 두 번째 div(4 줄 포함)의 높이가 모두 최대임을 알 수 있습니다. 어떻게 알 수 있습니까? 누군가 도와 주시겠습니까?

지금까지 시도했습니다.

$("div.panel").height()1st의 높이를 반환합니다 div.

답변:


213

사용 .map()하고 Math.max.

var maxHeight = Math.max.apply(null, $("div.panel").map(function ()
{
    return $(this).height();
}).get());

읽기에 혼란 스러우면이게 더 명확 할 수 있습니다.

var heights = $("div.panel").map(function ()
    {
        return $(this).height();
    }).get();

maxHeight = Math.max.apply(null, heights);

1
이것은 가장 높은 높이를 찾지 만 실제 요소에 대한 참조는 찾지 못합니다.
Vincent Ramdhanie

네가 옳아; OP가 요소도 원하는지 확실하지 않았습니다. 이 경우 귀하의 답변이 작동합니다.
Matt Ball

3
@MattBall 왜 get 기능이 필요한지 물어봐도 될까요? 그것은 무엇을하고 그 목적은 무엇입니까?
chodorowicz 2014 년

2
@chodorowicz 당신이 물어서 기쁩니다. 두 번째 제목 아래 에서이 답변을 참조하십시오 .
Matt Ball

1
@MattBall 감사합니다. 그래서 jQuery .map은 배열과 같은 객체를 반환하고 get .get은 그것을 배열로 바꿉니다. 그러나 Math.max는이 두 유형 모두에서 쉽게 작동하는 것으로 보이므로 (Chrome 콘솔에서 테스트)이 경우 .get은 불필요 해 보입니다. 아니면 내가 틀렸나 요?
chodorowicz 2014 년

20

게시 한 html은 <br>실제로 높이가 다른 div를 갖기 위해 일부 를 사용해야합니다 . 이렇게 :

<div>
    <div class="panel">
      Line 1<br>
      Line 2
    </div>
    <div class="panel">
      Line 1<br>
      Line 2<br>
      Line 3<br>
      Line 4
    </div>
    <div class="panel">
      Line 1
    </div>
    <div class="panel">
      Line 1<br>
      Line 2
    </div>
</div>

그 외에도 최대 높이로 div에 대한 참조를 원한다면 다음을 수행 할 수 있습니다.

var highest = null;
var hi = 0;
$(".panel").each(function(){
  var h = $(this).height();
  if(h > hi){
     hi = h;
     highest = $(this);  
  }    
});
//highest now contains the div with the highest so lets highlight it
highest.css("background-color", "red");

이것에주의하세요. 만약 당신이 ( .height이 경우 처럼) jQuery 메소드를 사용하지 않는다면 , 그것을 역 참조해야합니다. 예 :`$ (this) [0] .scrollHeight;`
rogerdpack

5

여러 위치에서 재사용하려는 경우 :

var maxHeight = function(elems){
    return Math.max.apply(null, elems.map(function ()
    {
        return $(this).height();
    }).get());
}

그런 다음 다음을 사용할 수 있습니다.

maxHeight($("some selector"));

1

function startListHeight($tag) {
  
    function setHeight(s) {
        var max = 0;
        s.each(function() {
            var h = $(this).height();
            max = Math.max(max, h);
        }).height('').height(max);
    }
  
    $(window).on('ready load resize', setHeight($tag));
}

jQuery(function($) {
    $('#list-lines').each(function() {
        startListHeight($('li', this));
    });
});
#list-lines {
    margin: 0;
    padding: 0;
}

#list-lines li {
    float: left;
    display: table;
    width: 33.3334%;
    list-style-type: none;
}

#list-lines li img {
    width: 100%;
    height: auto;
}

#list-lines::after {
    content: "";
    display: block;
    clear: both;
    overflow: hidden;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>

<ul id="list-lines">
    <li>
        <img src="http://img2.vetton.ru//upl/1000/346/138/vetton_ru_sddu7-2560x1600.jpg" alt="" />
        <br /> Line 1
        <br /> Line 2
    </li>
    <li>
        <img src="http://img2.vetton.ru//upl/1000/346/138/vetton_ru_mixwall66-2560x1600.jpg" alt="" />
        <br /> Line 1
        <br /> Line 2
        <br /> Line 3
        <br /> Line 4
    </li>
    <li>
        <img src="http://img2.vetton.ru//upl/1000/346/138/vetton_ru_sddu7-2560x1600.jpg" alt="" />
        <br /> Line 1
    </li>
    <li>
        <img src="http://img2.vetton.ru//upl/1000/346/138/vetton_ru_mixwall66-2560x1600.jpg" alt="" />
        <br /> Line 1
        <br /> Line 2
    </li>
</ul>


1

ul, li {
  list-style: none;
  margin: 0;
  padding: 0;
}

ul {
  display: flex;
  flex-wrap: wrap;
}

ul li {
  width: calc(100% / 3);
}

img {
  width: 100%;
  height: auto;
}
<ul>
  <li>
    <img src="http://img2.vetton.ru//upl/1000/346/138/vetton_ru_sddu7-2560x1600.jpg" alt="">
    <br> Line 1
    <br> Line 2
  </li>
  <li>
    <img src="http://img2.vetton.ru//upl/1000/346/138/vetton_ru_mixwall66-2560x1600.jpg" alt="">
    <br> Line 1
    <br> Line 2
    <br> Line 3
    <br> Line 4
  </li>
  <li>
    <img src="http://img2.vetton.ru//upl/1000/346/138/vetton_ru_sddu7-2560x1600.jpg" alt="">
    <br> Line 1
  </li>
  <li>
    <img src="http://img2.vetton.ru//upl/1000/346/138/vetton_ru_mixwall66-2560x1600.jpg" alt="">
    <br> Line 1
    <br> Line 2
  </li>
</ul>



0

표준 JavaScript에서 또는 forEach ()를 사용하지 않고 완전히 정렬하는 데 관심이있는 경우 :

var panels = document.querySelectorAll("div.panel");

// You'll need to slice the node_list before using .map()
var heights = Array.prototype.slice.call(panels).map(function (panel) {
    // return an array to hold the item and its value
    return [panel, panel.offsetHeight];
}),

// Returns a sorted array
var sortedHeights = heights.sort(function(a, b) { return a[1] > b[1]});

0

내가 말하고 싶은 가장 쉽고 명확한 방법은 다음과 같습니다.

var maxHeight = 0, maxHeightElement = null;
$('.panel').each(function(){
   if ($(this).height() > maxHeight) {
       maxHeight = $(this).height();
       maxHeightElement = $(this);
   }
});

0

이것은 어떤면에서 도움이 될 수 있습니다. @diogo의 일부 코드 수정

$(window).on('load',function(){

// get the maxHeight using innerHeight() function
  var maxHeight = Math.max.apply(null, $("div.panel").map(function ()                                                        {
    return $(this).innerHeight();
  }).get());
  
// Set the height to all .panel elements
  $("div.panel").height( maxHeight );
  
});
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.