CSS: no DIV width when display set to none

2019-03-01 09:40发布

I'm on the process of making a dropdown widget. The menu the expands down is set to the same width as the parent (using jQuery).

The widget is working as expected, until however, you place it inside a DIV container with inital display set to none. When this container is shown, all the dropdown width's according to jQuery are zero... If the container is shown by default, all works.

Hopefully my fiddle will better illustrate what I mean: http://jsfiddle.net/ruFzR/ On the results pane; the top dropdown is outside of the container, the bottom inside it. Besides some obvious styling issues, the width is not expanding.

5条回答
乱世女痞
2楼-- · 2019-03-01 10:05

If you're going to use display:none: you have to show the menu first, calculate the width, then hide it. Alternatively, you could hide with absolute positioning, which should report the width correctly since the element has been painted. Example: position: absolute; top: -999em;

查看更多
放我归山
3楼-- · 2019-03-01 10:06

the .width() is processed by the browser that's why you get "0" try with the attribute instead

 $('#elt').attr('width');
查看更多
一纸荒年 Trace。
4楼-- · 2019-03-01 10:10

If you need the width of something that's hidden and you can't un-hide it for whatever reason, you can clone it, change the CSS so it displays off the page, make it invisible, and then measure it. The user will be none the wiser if it's hidden and deleted afterwards.

Example:

$itemClone = $('.hidden-item').clone().css({
        'visibility': 'hidden',
        'position': 'absolute',
        'z-index': '-99999',
        'left': '99999999px',
        'top': '0px'
    }).appendTo('body');
var width = $itemClone.width();
$itemClone.remove();
查看更多
冷血范
5楼-- · 2019-03-01 10:11

You can avoid the width issue caused by display: none; by using visibility: hidden; instead. Use visibility: visible; to make it visible.

The element stays within your content flow (same size, etc.) while it's simply invisible.

查看更多
放我归山
6楼-- · 2019-03-01 10:11

From the example i am not sure what the problem is ..

But you should be set (in that example) with

.splitButton2 > div{width:100%;}

This is equivalent to the jQuery code you wrote, has no downsides (width is 0 if the element is display:none, javascript dependency) and is easier on the browser ..

查看更多
登录 后发表回答