jQuery通过display:none属性获取元素的高度

时间:2018-11-01 00:37:35

标签: javascript jquery css

是否有一种简单的方法来获取内部具有隐藏子div的父div的高度?如果没有,那么实现这种结果的困难方法是什么?

PS:我知道这个话题可能是重复的,但是我发现的其他话题都给出了负面的最佳答案。

export class Action1 implements Action {}

export class Action2 implements Action {}

export type ActionsUnion =
  | Action1
  | Action2;
ActionsUnion
it('should have the correct types', () => {
  expect(typeof Action1).toEqual(ActionsUnion);
  expect(typeof Action2).toEqual(ActionsUnion);
});

1 个答案:

答案 0 :(得分:1)

当未显示子元素时,您当然可以获取父元素的高度,但是听起来好像您想在考虑所有子元素的高度时获取父元素的高度。在这种情况下,您可以隐藏但显示子级,抓住高度,然后还原:

/* parentSelector: selector we wish to know its height
 * childSelector:  children to display when measuring parent
 */ 
function getHeight(parentSelector, childSelector) {
    var parent = $(parentSelector);
    var children = parent.children(childSelector);
    var styleState = [];

    //set state
    children.each(function (i) {
        let c = $(this);
        styleState[i] = c.css(['display', 'visibility']);
        c.css({ display: '', visibility: 'hidden' });
    });

    var height = parent.css('height');
    
    //revert state
    children.each(function (i) {
        let { display, visibility } = styleState[i];
        $(this).css({ display, visibility });
    });

    return height;
}

$('#test > div').hide();
console.log(getHeight('#test', 'div'));
#test { background: brown; padding: 1em }
#test > div { height: 50px; background: yellow; margin: 1em 0 }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="test">
    <span>span</span>
    <div>div</div>
    <div>div</div>
</div>

我希望这会有所帮助!