【问题标题】:jquery margin grid layoutjquery边距网格布局
【发布时间】:2013-09-19 08:59:49
【问题描述】:

我正在创建一个使用百分比来调整元素大小的响应式网格系统系统。我尝试使用浮点数、内联块和表格来构建它。我确定我想坚持使用 inline-block,因为它允许我将项目垂直和水平居中。我在不使用边距的情况下构建了我的设计。我正在使用边框模型,因此填充和边框不会折叠行。

但是,我想升级我的网格系统以允许您在不破坏行的情况下设置边距。基本上是一个 jquery 自定义构建的“box-sizing: margin-box;”。

我希望我可以使用 jquery 从容器的百分比宽度中减去边距的百分比宽度。然而,这本身并不能很好地工作,因为 inline-block 增加了额外的空白。因此,除了我目前的计划之外,我还使用 jquery 从 margin-right 中减去额外的空白。我真的让它工作了!它可以满足我的要求,但我遇到了一个小问题。

计算不够精确,行最终会出现几个像素之间的差异。这意味着我在每一行的末尾都没有得到直线。整个行的长度不同。如何使计算足够精确以准确排列?

代码如下:

     boxsizing = function(container){

     jQuery(container).each(function() {
      var el = jQuery(this);

      el.css('width', '');
      el.css('margin-right', '');

      var parentWidth = el.parent().width();

      var childWidth = el.outerWidth(false);

      //finds ratio of child container to parent container
      var childDecimal = (childWidth / parentWidth);


      //converts child container to a decimal
      childDecimal = Math.round(childDecimal*10000);


      //gets font size
      var fontSize = el.css('font-size');
      //removes px from the end
      var fontSize = fontSize.slice (0, -2);
      //calculates white space on the right of each div
      var whiteSpace = 0.29*fontSize;
      var fontDecimal = whiteSpace / parentWidth;
      //converts white space to a decimal
      fontDecimal = Math.round(fontDecimal*10000)

      //subtracts extra white space from margin-right
      var newMarginRight = el.css('margin-right');
      var newMarginRight = newMarginRight.slice (0, -2);
          newMarginRight = Math.round(newMarginRight);
          newMarginRight = newMarginRight - whiteSpace;
          newMarginRight = newMarginRight / parentWidth;
          newMarginRight = Math.round(newMarginRight*10000);
          newMarginRight = newMarginRight/100;


      //finds margin to parent ratio
      var marginDecimal = (el.outerWidth(true) - childWidth)/parentWidth;
      //converts margin to decimal form
      marginDecimal = Math.round(marginDecimal*10000);

      //take previous width and subtract margin from it
      var newWidth = (childDecimal - marginDecimal)/100;

      //set the element's width to the new calcualted with and set margin right to the updated value
      el.css('width', newWidth + "%");
      el.css('margin-right', newMarginRight + "%");
     });
    }


    jQuery(window).load(function() {
        boxsizing('.margins');
    });

【问题讨论】:

    标签: jquery grid margin


    【解决方案1】:

    所以让我直截了当地说,你打算使用 jQuery 来“修复”一个网格框架吗?这将是收集您的想法并返回绘图板的好时机。

    所有网格系统总是涉及妥协,有些在空白方面做得不太好(内联网格),有些需要残留类(浮动网格),有些只是粗略的(表格网格)。但是他们都同意一件事,他们使用 CSS

    如果您想要一个 javascript 网格,那么您的标记实际上可以是任何东西。你可以制作实际的<row><column> 元素,因为谁在乎呢,反正你只会用javascript hotdog。没有人这样做的原因很简单,在内容完全加载并且您的脚本将其全部整理好之前,浏览器没有任何东西可以显示给用户。

    任何依赖于 javascript(以及扩展为 jQuery)的网格系统都必须做以下两件事之一:

    1. 隐藏页面内容,直到一切都“恰到好处”才能全部绘制出来。
    2. 显示一个乱七八糟的页面,然后将其全部修复。

    通常认为这些选项都不可接受。所以请随意设计自己的网格系统,上帝知道the internet needs more of them,但请使用 CSS。

    【讨论】: