【问题标题】:force div height to nearest multiple of the background image height将 div 高度强制为最接近背景图像高度的倍数
【发布时间】:2013-08-13 10:13:27
【问题描述】:

有点棘手的情况要解释。基本上,我试图在我的网站内容 div 下放置的整体图像是一个杂乱无章的盒子,带有可以弯曲和弯曲的邋遢边框。

到目前为止我得到的是这样的(不相关的代码已删除)

<div class="content-top"><img src="content-top.png"></div>
<div id="content"> <!-- WORDPRESS LOADS CONTENT HERE --> </div>
<div class="content-bottom"><img src="content-bottom.png"></div>

CSS:
#content {
  background: url("assets/images/content-bg.png") repeat-y scroll 0 0 transparent;
}

content-bg.png 图像的高度为 300 像素,是可重复的图像,可在两侧创建带图案的边框。

问题是 content-bottom.png 图像仅在放置在这些 300 像素图块之一的末尾时才看起来正确。如果页面内容的高度导致仅显示最后一个背景图块的一半,则行不匹配。

输入这个我怀疑答案在于 CSS,相反我需要一个 javascript/jquery 解决方案,但至于如何做到这一点的细节我不确定。

【问题讨论】:

    标签: javascript css background background-image


    【解决方案1】:

    这是您的问题的解决方案。它会将内容容器展开到下一个高度,即 300 的倍数

    纯 JavaScript 版本

    var e = document.getElementById('content');
    var height = e.clientHeight;
    var newHeight = 300 * Math.ceil(height / 300);
    e.setAttribute('style', 'height: ' + newHeight + 'px;');
    

    演示

    Try before buy

    jQuery 版本

    var e = $('#content');
    e.css('height', 300 * Math.ceil(e.height() / 300));
    

    演示

    Try before buy

    【讨论】:

      【解决方案2】:

      这是一个支持动态背景图像的 i-can't-sleep-solution:

      var content = $('#content'),
          height = content.height(),
          fixedImageHeight = null,     //.. number (pick one)
          srcImage = null,             //.. url to image (pick one)
          imageHeight = function() {
              return fixedImageHeight || function() {
                  var image = new Image();
                  image.src = srcImage;
                  return image.height;
              }();
          }(),
          neededPadding = (height > imageHeight) 
              ? height % imageHeight
              : imageHeight - height;
      
      content.height(height + neededPadding);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-04-14
        • 2022-01-21
        • 2013-03-04
        • 2019-06-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多