jQuery,切换div,CSS间距问题 [英] jQuery, toggling div, CSS spacing issue

查看:118
本文介绍了jQuery,切换div,CSS间距问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个标记:

<div class="myToggledDiv">
    <div>content</div>
</div>

<div style="margin-top: 10px;">
    content
</div>

通过jQuery,我正在做一个.slideToggle来显示/隐藏顶部div。

Via jQuery, I'm doing a .slideToggle to show/hide the top div.

我希望两个div之间始终有10px的空间,无论是折叠还是展开。

I'd like there to be the 10px space between the two divs at all times, whether collapsed or expanded.

然而,行为是当顶部div向下滑动时,10px边距仍然存在,但是一旦顶部div完成向下滑动,10px边距就会消失。这或许似乎是一个保证金崩溃问题。

The behavior, however is that as the top div slides down, the 10px margin remains but as soon as the top div is finished sliding down the 10px margin disappears. It appears to be a margin collapse issue perhaps.

我想出的解决方案是:

<div class="myToggledDiv">
    <div>content</div>
</div>

<div style="font-size: 1px">&nbsp;</div>

<div style="margin-top: 10px;">
    content
</div>

& nbsp;是关键,因为需要在div中内容来分离两者并保留10px的保证金。

The &nbsp; is the key as there needs to be content in the div to 'separate' the two and retain the 10px of margin.

我尝试了.clearfix:after方法,但是在这种情况下不起作用,所以这可能是一个以jQuery为中心的问题。有没有人遇到过这个并发现了比额外div更优雅的解决方案?

I tried the .clearfix:after approach as well, but that doesn't work in this scenario, so perhaps this is a jQuery centric issue. Has anyone ran into this and found a more elegant solution than the extra div?

推荐答案

信不信由你,你只需要将 1px 填充添加到父容器的顶部。问题是,在 slideToggle 结束时,第一个 div 设置为 display:none 这会导致第二个div对父母进行轻击。现在,它只是一个CSS错误。如果在父项上没有设置填充,子项边距将在父项的,并向下推两个项目。通过将 1px 边距应用于父元素,可以强制边距保留在元素内:

Believe it or not, you just need to add a 1px padding to the top of the parent container. The problem is, at the end of slideToggle the first div is set to display:none which causes the second div to be smack dab against the parent. Now, its just a CSS bug. If there is no padding set on the parent item, the child items margin will go outside of the parent, and push both items down. By applying a 1px margin to the parent element, you force the margin to stay inside the element:

<body style="padding-top: 1px">
  <div class="myToggledDiv">
      <div>content</div>
  </div>

  <div style="margin-top: 10px;">
      content
  </div>
</body>

显然,你想删除所有这些内联样式并使用单独的样式表和id / classes作为需要。

Obviously, you want to remove all of those inline styles and use a separate stylesheet and id's/classes as needed.

如果您需要抵消额外的填充(取决于您的布局),您可能只能使用它:

If you need to offset the extra padding (depending on your layout) you might just be able to use this:

{ margin-top: -1px; padding-top: 1px }

这篇关于jQuery,切换div,CSS间距问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆