如何使<section>的内容宽度为零?</section>

时间:2012-07-01 06:33:31

标签: jquery

我有以下HTML:

<section id="sidebar" class="grid_3">
<section id="content" class="grid_9">

我使用jQuery将其更改为:

<section id="sidebar" class="" style="width: 0px;">
<section id="content" class="grid_12">

然而,似乎侧边栏id的部分仍然有一些宽度,并且其中的元素出现。

有什么方法可以使用jQuery使id = sidebar的内容不可见?我认为给它宽度为0px会使它工作,但似乎没有。我想知道的是将显示设置为隐藏或可见性,但我不确定隐藏和可见之间的差异?也不确定jQuery秀和隐藏。在这种情况下哪个最好?

4 个答案:

答案 0 :(得分:2)

$("#sidebar").hide() // sets the position of the element to `display: none`;
$("#sidebar").show() // sets the position of the element to `display: block`;
$("#sidebar").css('width', '0 !important') // sets the width of the element to `0` and overrides other element's width properties;
$("#sidebar").css('visibility', 'hidden') // The element is invisible but still takes up space;
  

how can I detect if the display is set to "none" with jQuery?

试试这个:

if ($('.grid_3').is(':hidden')) { // if the element is hidden do something here}
if ($('.grid_3').is(':visible')) { // if the element is visible do something here}

答案 1 :(得分:1)

visibility: hidden隐藏元素但保留在文档流中。 display: none将隐藏和删除常规流中的元素。 opacity: 0可用于其他情况。在某些情况下使用的另一个选项是position: absolute元素,并通过left: -9999px将其移到一边来隐藏它。选择其中一个选项,width: 0根本不适合任何情况,至少根据我的经验。

答案 2 :(得分:0)

$('#sidebar').hide()会隐藏侧边栏,但是您必须知道(正如@elclanrs所解释的)这会从文档流中删除该元素,因此如果您的布局需要侧边栏的存在,使用$('#sidebar').css('visibility', 'none')

答案 3 :(得分:0)

正如其他人指出的那样:

  • visibility: hidden;:隐藏元素及其内容,但不断占用空间(就像设置opacity: 0;);
  • display: none;:隐藏对象并将其从流中移除,为其他元素释放空间(例如:如果在上面的元素上设置它,则下面的元素将向上移动以占据其空间);

要设置宽度为零的元素,并隐藏将overflow属性设置为hidden

所需的内容
  • overflow: hidden:隐藏溢出的内容(扩展到其父级边框之外),防止它在其父级外部进行处理。

使用jQuery,我使用animate()重新编写任务:

$("#sidebar").css("overflow", "hidden").animate({ width: "hide" }, "fast");

您可以在此处使用“切换”或“显示”作为宽度参数。