jquery边距网格布局

时间:2013-09-14 22:52:19

标签: jquery grid margin

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

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

我希望我可以使用jquery从容器的百分比宽度中减去边距的百分比宽度。但是,这本身并不能很好地工作,因为内联块会增加额外的空白区域。所以除了我目前的计划,我使用jquery从mar​​gin-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');
    });

1 个答案:

答案 0 :(得分:1)

所以,让我直截了当,你将使用jQuery“修复”网格框架?这是收集你的想法并回到绘图板的好时机。

所有网格系统总是涉及妥协,有些不能用空格(内联网格)做得很好,有些需要退化类(浮点网格),有些只是粗略(表格网格)。但他们都同意一件事,他们使用CSS

如果你想要一个javascript网格,那么你的标记可以是任何东西。您可以制作实际的<row><column>元素,因为无论如何,您只关心javascript热狗。没有人这样做的原因很简单,直到内容完全加载并且你的脚本已经全部排序,浏览器没有任何东西可以向用户显示。

依赖于javascript(以及扩展名为jQuery)的任何网格系统都必须执行以下两项操作之一:

  1. 隐藏页面内容,直到所有内容都“恰到好处”为止。
  2. 显示一个乱糟糟的页面,然后猛拉它以解决它。
  3. 这些选项通常都不被认为是可以接受的。所以随意设计自己的网格系统,领主知道the internet needs more of them,但用CSS做。