How do you find the dimensions of a “display: none” element?

后端 未结 6 2045
眼角桃花
眼角桃花 2021-02-13 19:04

I have some child elements inside a div that gets the CSS display: none applied to it and I want to find out what the child element dimensions are. How can I do thi

6条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-13 19:21

    You can't get dimensions of an element with display: none, because since it's hidden, it doesn't take any space, so it has no dimensions. The same apply to its children.

    You can instead make the element visible for a while, check the child dimensions and make the element invisible back. As pointed by @JanDvorak:

    Browsers don't repaint while synchronous Javascript is running, so the element should never appear on-screen.

    Example code:

    var o = document.getElementById('output');
    var wmd1 = document.getElementById('whats-my-dims1');
    var wmd2 = document.getElementById('whats-my-dims2');
    var hiddenDiv = document.getElementById("some-hidden-div");
    hiddenDiv.style.display = "block";
    o.innerHTML = 'wmd1: "' + wmd1.clientWidth + '", "' + wmd1.clientHeight + '", wmd2: "' + wmd2.clientWidth + '", "' + wmd2.clientHeight + '"';
    hiddenDiv.style.display = "";
    

    See demo on JS Fiddle.

提交回复
热议问题