在中间而不是结尾处包装一行代码块(CSS / JS / jQ)

时间:2018-08-27 23:26:03

标签: javascript jquery html css

缩小的父级如何封装一行内联块,从而导致行数相等(或几乎相等)?

所以不要像这样包装:

enter image description here

像这样包装:

enter image description here

如果块的数量不均匀,例如:

enter image description here

3 个答案:

答案 0 :(得分:0)

您可以使用CSS网格grid-template-columns和@media(如果要按屏幕宽度进行换行),也可以在JS中使用docment.getElementById('bottomblocks').style.gridTemplateColumns变量来实现此目的。 (如果我理解正确)

我在这里用JS编写了一个示例: https://jsfiddle.net/Lhbqdt2z/

您可以从我开始的地方了解它:Coding Tech Talk

或者仅来自W3Schools

Moz:// a有一个很好的例子here

答案 1 :(得分:0)

我刚刚写的他很有趣……假设您想要一种“增强包装”行为,该行为由其子项的一半包裹,而不是正常的浮动。

与其说是最佳的最佳实践答案,倒不如说是一篇“论文”。 ;)

$(window).on("load resize",function(){
  $(".container div").css({"clear":"initial"});
  var wrapped = false;
  var wrappedAt = 0;
  var wrappedNtimes =0;
  var pos = $(".container div").first().offset();
  var n = $(".container div").length;

  $(".container div").each(function(index){
    if(!wrapped){

      if( ($(this).offset().top != pos.top)){
        console.log("Wrapped at "+index+" out of "+n);
        wrapped = true;
        wrappedAt = index;
        wrappedNtimes++;
      }
      pos=$(this).offset();
    }
  });

  if(wrapped){
    // Force enhanced wrapping... .oO(lol)
    console.log("--"+wrappedAt+"--");
    var half = Math.ceil(n/(wrappedNtimes+1));

    $(".container div").each(function(){
      if( $(this).index() != 0 && ($(this).index())%half == 0){
        $(this).css({"clear":"left"});  // zero-based.
      }
    });
  }
});

CodePen demo

答案 2 :(得分:0)

这是在每行末尾插入<br>元素的解决方案。只要需要包装这些块,就可以将此代码放入要运行的函数中。

// Make sure that the last row of blocks doesn't have 2 less blocks than all
// the previous rows. Assume that all blocks are equal size.
var blocks = sharing.find('.btn');

//what's the parent width
var parentWidth = blocks.parent().width();

//how many blocks can fit in such a width
var maxNumOfBlocksInOneRow = Math.floor(parentWidth / blocks.outerWidth(true));

//repeatable code
var calcNumOfBlocksInLastRow = function(){
  var lastRowFull = blocks.length % maxNumOfBlocksInOneRow ? false : true;
  if (lastRowFull) {
    return maxNumOfBlocksInOneRow;
  } else {
    return blocks.length % maxNumOfBlocksInOneRow;
  }
}

//do we have more blocks than row's maximum?
if (blocks.length > maxNumOfBlocksInOneRow) {
  //how many blocks would the last row have
  var numOfBlocksInLastRow = calcNumOfBlocksInLastRow();

  //if the last row is missing more than 1 block, try with 1 less block in each row
  while (numOfBlocksInLastRow < maxNumOfBlocksInOneRow - 1) {
    maxNumOfBlocksInOneRow--;
    numOfBlocksInLastRow = calcNumOfBlocksInLastRow();
  }

  //insert <br> at the end of each row
  jQuery('<br>').insertAfter(blocks.filter(':nth-child(' + maxNumOfBlocksInOneRow + 'n)'));
}