How do I get the real .height() of a overflow: hidden or overflow: scroll div?

前端 未结 6 1523
庸人自扰
庸人自扰 2020-11-28 20:29

I have a question regarding how to get a div height. I\'m aware of .height() and innerHeight(), but none of them does the job for me in this case.

6条回答
  •  鱼传尺愫
    2020-11-28 20:46

    I have just cooked up another solution for this, where it's not longer necessary to use a -much to high- max-height value. It needs a few lines of javascript code to calculate the inner height of the collapsed DIV but after that, it's all CSS.

    1) Fetching and setting height

    Fetch the inner height of the collapsed element (using scrollHeight). My element has a class .section__accordeon__content and I actually run this in a forEach() loop to set the height for all panels, but you get the idea.

    document.querySelectorAll( '.section__accordeon__content' ).style.cssText = "--accordeon-height: " + accordeonPanel.scrollHeight + "px";
    

    2) Use the CSS variable to expand the active item

    Next, use the CSS variable to set the max-height value when the item has an .active class.

    .section__accordeon__content.active {
      max-height: var(--accordeon-height);
    }
    

    Final example

    So the full example goes like this: first loop through all accordeon panels and store their scrollHeight values as CSS variables. Next use the CSS variable as the max-height value on the active/expanded/open state of the element.

    Javascript:

    document.querySelectorAll( '.section__accordeon__content' ).forEach(
      function( accordeonPanel ) {
        accordeonPanel.style.cssText = "--accordeon-height: " + accordeonPanel.scrollHeight + "px";
      }
    );
    

    CSS:

    .section__accordeon__content {
      max-height: 0px;
      overflow: hidden;
      transition: all 425ms cubic-bezier(0.465, 0.183, 0.153, 0.946);
    }
    
    .section__accordeon__content.active {
      max-height: var(--accordeon-height);
    }
    

    And there you have it. A adaptive max-height animation using only CSS and a few lines of JavaScript code (no jQuery required).

    Hope this helps someone in the future (or my future self for reference).

提交回复
热议问题