【问题标题】:How to continue the background of a div on another div/span?如何在另一个 div/span 上继续一个 div 的背景?
【发布时间】:2014-02-27 08:36:09
【问题描述】:

在我的网页中,我有一个带有背景的块,下面有一个按钮,应该继续背景。

这是一个例子。左图是我的网页现在的样子,右图是网页应该的样子。可以看到按钮上的背景继续。

我的代码结构是这样的:

<div id="section-1">
  <div class="shown-content">
    <div class="background"></div>
    <div class="content">
      ... here are shown contents ...
    </div>
  </div>

  <div class="hidden-content">
    ... here are hidden contents ...
  </div>

  <div class="button-content">
    <span class="button">FOLD OUT</span>
  </div>
</div>

功能是当你点击按钮时,它会触发 JQuery slideToggle 并显示/隐藏 hidden-content div。

我的想法是将按钮背景设置为与内容背景相同的宽度和高度,然后将其放置在适当的位置。但是我有点迷茫,因为我没有找到任何方法,也许你知道更好的方法。

【问题讨论】:

  • 你能不能做一个 jsfiddle.net 让我们看看有什么问题。 :)
  • jycr:有一张大图显示出了什么问题! ;)

标签: javascript jquery css background background-image


【解决方案1】:

假设您的图片占位符高度为 100 像素,按钮为 30 像素。

假设您的按钮始终位于主图像 div 的中心。

然后你需要一个 130px 高的图片,其中背景位置设置为顶部居中,按钮背景位置设置为底部居中。

样本

.imgdiv {
    background-position: center top
}

.buttdiv {
    background-position: center bottom
}

如果您的按钮不在中心,则需要调整背景位置的“中心”部分以使其与主图像匹配

【讨论】:

  • 我必须使用 JavaScript 调整按钮的位置和背景大小。但它有效。
【解决方案2】:

您最初的想法可能是最好的解决方案。

使用背景位置正确定位您的 div。

.button-content{
    background: url('') no-repeat 200 100%;
}

不重复后的数字是背景图片的X位置Y位置。

【讨论】:

    【解决方案3】:

    我找到了这个解决方案,希望对你有所帮助。

    将折叠按钮绝对放置在相对定位的#section-1
    在绝对放置时,它只会占用它需要的宽度。然后我们使用伪类:before:after 用主体的背景色(在我的示例中为白色)填充左右的空间。

    HTML 看起来像这样(可以用您的其余代码扩展):

    <div id="section-1">
        <div class="hidden-content">
            hidden content
        </div>
        <div class="button">
            Fold out
        </div>
    </div>
    

    还有 CSS:

    #section-1 {
        min-height: 100px; /*use min-height so it will expand */
        background: url('pic.jpg');
        position: relative;
        padding-bottom: 30px; /* height of .button */
        overflow: hidden; /* to hide the :before and :after */
    }
    .button {
        position: absolute;
        bottom: 0;
        right: 20px;
        height: 30px;
        width: 75px;
        text-align: center;
    }
    .button:before, .button:after {
        content: ' ';
        background: white;
        position: absolute;
        width: 1000px;
        left: -1000px;
        height: 30px;
    }
    .button:after {
        left: 100%;
    }
    .hidden-content {
        display: none;
    }
    

    还有一个demo

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-11-14
      • 1970-01-01
      • 1970-01-01
      • 2013-04-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多