找到隐藏元素的"潜在"宽度

Gau*_*sie 32 javascript css jquery

我目前正在扩展lavalamp插件以处理下拉菜单,但我遇到了一个小问题.我需要知道offsetWidth隐藏的元素.现在显然这个问题毫无意义,而我正在寻找的是offsetWidth它没有隐藏的元素.

解决方案是显示它,抓住宽度,然后再次隐藏?肯定有更好的办法...

Pet*_*ley 38

我唯一能想到的是显示它(或它的克隆)以允许检索offsetWidth.

对于此测量步骤,只需使其位置绝对,其x或y值为负值,因此它将呈现但不会对用户可见.


bob*_*nce 36

具有CSS的元素的宽度visibility: hidden是可测量的.只有当它display: none根本没有渲染时才会出现.因此,如果确定元素将被绝对定位(因此它们在显示时不会导致布局更改),只需使用css('visibility', 'hidden')隐藏元素而不是,hide()您应该可以测量宽度.

否则,是的,show-measure-hide确实有效.


ajb*_*ven 12

您可以使用以下函数来获取隐藏容器内元素的外部宽度.

$.fn.getHiddenOffsetWidth = function () {
    // save a reference to a cloned element that can be measured
    var $hiddenElement = $(this).clone().appendTo('body');

    // calculate the width of the clone
    var width = $hiddenElement.outerWidth();

    // remove the clone from the DOM
    $hiddenElement.remove();

    return width;
};
Run Code Online (Sandbox Code Playgroud)

您可以更改.outerWidth().offsetWidth()您的具体情况.

该函数首先克隆元素,将其复制到可见的位置.然后它检索偏移宽度,最后删除克隆.以下代码段说明了此功能完美的情况:

<style>
    .container-inner {
        display: none;
    }

    .measure-me {
        width: 120px;
    }
</style>

<div class="container-outer">
    <div class="container-inner">
        <div class="measure-me"></div>
    </div>
</div>
Run Code Online (Sandbox Code Playgroud)

请注意,如果有一个CSS应用于元素,如果它是body的直接后代,则会更改将不会应用的元素的宽度,则此方法将不起作用.所以这样的事情意味着该功能不起作用:

.container-outer .measure-me {
    width: 100px;
}
Run Code Online (Sandbox Code Playgroud)

你要么需要:

  • 改变CSS选择器的特异性即. .measure-me { width: 100px; }
  • 更改appendTo()以将克隆添加到CSS也将应用于克隆的位置.确保您放置它的位置,该元素将是可见的:.appendTo('.container-outer')

同样,此函数假定元素仅被隐藏,因为它位于隐藏容器内.如果元素本身是display:none,您可以简单地添加一些代码,以便在检索克隆的偏移宽度之前使克隆可见.像这样的东西:

$.fn.getHiddenOffsetWidth = function () {
    var hiddenElement $(this)
        width = 0;

    // make the element measurable
    hiddenElement.show();

    // calculate the width of the element
    width = hiddenElement.outerWidth();

    // hide the element again
    hiddenElement.hide();

    return width;
}
Run Code Online (Sandbox Code Playgroud)

这可以在这样的情况下工作:

<style>
    .measure-me {
        display: none;
        width: 120px;
    }
</style>

<div class="container">
    <div class="measure-me"></div>
</div>
Run Code Online (Sandbox Code Playgroud)

  • 有趣,但它不适用于任何类型的样式继承或容器指定的样式。 (2认同)