jQuery 隐藏元素,同时在页面布局中保留其空间
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6393632/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery hide element while preserving its space in page layout
提问by slandau
Is there a way in jQuery where I can hide an element, but not change the DOM when it's hidden? I'm hiding a certain element but when it's hidden, the elements below it move up. I don't want that to happen. I want the space to stay the same, but the element to be shown/hidden at will.
在 jQuery 中有没有一种方法可以隐藏元素,但在隐藏时不能更改 DOM?我隐藏了某个元素,但是当它隐藏时,它下面的元素会向上移动。我不希望这种情况发生。我希望空间保持不变,但可以随意显示/隐藏元素。
Can I do this?
我可以这样做吗?
回答by Dr.Molle
Instead of hide()
, use:
代替hide()
,使用:
css('visibility','hidden')
hide()
sets the display
style to none
, which completely removes the element from the document flow and causes it to not take up space.
hide()
将display
样式设置为none
,这将完全从文档流中删除元素并使其不占用空间。
visibility:hidden
keeps the space as it is.
visibility:hidden
保持空间原样。
回答by Chad Levy
Try setting the visibility
to hidden
:
尝试设置visibility
为hidden
:
$("#id").css("visibility", "hidden");
回答by Sparky
display: none;
will take it out of the content flow so you'll see your other content move into the empty space left behind. (display: block;
brings it back into the flow pushing everything out of the way.)
display: none;
将把它从内容流中取出,这样你就会看到你的其他内容移动到留下的空白空间。(display: block;
将它带回到流程中,将所有东西都推开。)
visibility: hidden;
will keep it within the content flow taking up space but simply make it invisible. (visibility: visible;
will reveal it again.)
visibility: hidden;
将其保留在占用空间的内容流中,但只是使其不可见。(visibility: visible;
将再次揭示它。)
You'll want to use visibility
if you want your content flow to remain unchanged.
visibility
如果您希望您的内容流保持不变,您将需要使用。
回答by lunelson
in another answer it is noted that jQuery's fadeTo
does not set display:none
on completion so might also provide a solution here, rather than using fadeOut
for example:
在另一个答案中指出,jQueryfadeTo
不会display:none
在完成时设置,因此也可能在此处提供解决方案,而不是使用fadeOut
例如:
回答by joeytwiddle
I previously used opacity: 0
before I saw the visibility: hidden
trick.
opacity: 0
在我看到这个visibility: hidden
技巧之前,我以前使用过。
But in many cases opacity: 0
is problematic, because it lets you interact with the element, even though you can't see it! (As pointed out by DeadPassive.)
但是在很多情况下opacity: 0
是有问题的,因为它可以让您与元素进行交互,即使您看不到它!(正如DeadPassive指出的那样。)
Usually that's not what you want. But perhaps occasionally you might?
通常那不是你想要的。但也许偶尔你会?