Могу ли я передавать информацию по странице, а не через нее? - PullRequest
7 голосов
/ 17 марта 2010

Если у меня есть коллекция элементов div, я могу использовать CSS, чтобы они перемещались по странице и перетекали на следующую строку.

Вот простой пример:

<html>
  <head>
    <title>Flowing Divs</title>
    <style type="text/css">
      .flow {
        float: left;
        margin: 4em 8em;
      }
    </style>
  </head>
  <body>
    <div class="container">
      <div class="flow">Div 1</div>
      <div class="flow">Div 2</div>
      <div class="flow">Div 3</div>
      <div class="flow">Div 4</div>
      <div class="flow">Div 5</div>
      <div class="flow">Div 6</div>
      <div class="flow">Div 7</div>
      <div class="flow">Div 8</div>
    </div>
  </body>
</html>

Возможно ли, чтобы div проходил по странице, а не поперек нее, чтобы они текли вниз по столбцам, а не по линиям, но по-прежнему занимали то же место, что и при перемещении?

Так что для приведенного выше примера, если бы они слились в две строки по четыре div, могу ли я получить первый столбец, содержащий Div1 и Div2 вместо Div1 и Div5?

Ответы [ 4 ]

2 голосов
/ 17 марта 2010

Нет, это невозможно. Самый простой способ - создать отдельные столбцы, добавив DIV-обертку, а затем добавив содержимое в каждый столбец. Это также может быть сгенерировано динамически либо с помощью Javascript, либо на стороне сервера.

1 голос
/ 17 марта 2010

Нет, вы не можете, но вы можете расположить их так, как хотите, используя абсолютное позиционирование. Однако это означает, что вы должны явно указать положение каждого элемента, что обычно нежелательно.

Простая настройка разметки может сделать эту работу все же. Это то, что вы хотели увидеть?

<html>
  <head> 
    <title>Flowing Divs</title> 
    <style type="text/css">
      .container {
        float:left;
      }
      .flow {
        margin: 4em 8em; 
      } 
    </style> 
  </head> 
  <body> 
    <div class="container"> 
      <div class="flow">Div 1</div> 
      <div class="flow">Div 2</div> 
      <div class="flow">Div 3</div>
    </div>
    <div class="container">
      <div class="flow">Div 4</div> 
      <div class="flow">Div 5</div> 
      <div class="flow">Div 6</div>
    </div>
    <div class="container">
      <div class="flow">Div 7</div> 
      <div class="flow">Div 8</div> 
    </div> 
  </body> 
</html>
1 голос
/ 17 марта 2010

Быстро скинул это вместе.

#column1 {float:left}  
#column2 {float:left}  
div div{height:100px;width:100px;border:1px solid}

<div id="column1">    
      <div>1</div>  
      <div>2</div>  
</div>  
<div id="column2">  
      <div>3</div>  
      <div>4</div>  
</div>
0 голосов
/ 17 марта 2010

К сожалению, это не может быть сделано в чистом HTML / CSS. Ниже приведен пример того, как это может быть выполнено в JavaScript. Это может быть сделано более эффективным, но труднее учиться. Я не тестировал в IE / Safari, но работает в FF.

Как использовать: - Добавьте класс «контейнер» в контейнер потока. - вот и все

Наслаждайтесь:).

<html>
<head>
<title>Flowing Divs</title>

<style type="text/css">
.container {
    float: left;
    height: 1px;
}

.col {
    float: left;
}

#container-1 {
}

.flow {
    float: left;
    margin: 4em 8em;
    width: 200px;
    height: 100;
    overflow-y: hidden;
}
</style>

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.js"></script>
</head>

<body>

<div id="container-1" class="container">
    <div class="flow">Div 1</div>
    <div class="flow">Div 2</div>
    <div class="flow">Div 3</div>
    <div class="flow">Div 4</div>
    <div class="flow">Div 5</div>
    <div class="flow">Div 6</div>
    <div class="flow">Div 7</div>
    <div class="flow">Div 8</div>
    <div class="flow">Div 9</div>
    <div class="flow">Div 10</div>
    <div class="flow">Div 11</div>
    <div class="flow">Div 12</div>
    <div class="flow">Div 13</div>
    <div class="flow">Div 14</div>
    </div>

    <script type="text/javascript">

    /**
     * Setup some event handling and stuff
     */

    // Create flowing container after dom is populated
    $(document).ready(function()
    {
        createFlowingContainer('#container-1'); 
    });

    $(window).resize(function()
    {
        // Recreate flow for all containers without fixed heights
        $('.container-autosize').each(function(i, container)
        {
            var container = $(container);

            // Update container dimenions
            container.height($(window).height());    

            createFlowingContainer(container);
        });
    });

    /**
     * Magical function
     */

    createFlowingContainer = function(container)
    {
        var container = $(container);

        // Columns counter
        var colNum = 0;    

        // Some more counter vars, these reset when a new column is created
        var colHeight = 0;
        var colWidth = 0;
        var containerWidth = 0;

        var itemNum = 0;

        // Get height of container
        var containerHeight = container.height();

        // Has the container height been defined? 1px is the default height (as defined in the css)
        if (containerHeight == 1)
        {
            // Set the container height default value
            containerHeight = $(window).height();

            // Used to resize container on window resize events
            container.addClass('container-autosize');

            // Update container height
            container.height(containerHeight);
        }

        var containerElements = container.children('div :not(.col)');

        if (containerElements.length == 0)
        {
            containerElements = $('[itemNum]');
        }
        else
        {
            container.children('div').each(function(i, o)
            {
                $(o).attr('itemNum', itemNum);

                itemNum++;
            });
        }

        var containerTmp = container.clone();
        containerTmp.html('');    

        containerElements.each(function(i, ele)
        {
            var ele = $(ele);

            // Get the item's height with padding & margins included
            var eleWidth = ele.width();
            var eleHeight = ele.outerHeight(true);

            // Can the current column fit this item?
            if ((eleHeight + colHeight) > containerHeight)
            {
                // Reset calculated height of column & advance column pointer
                colHeight = 0;
                colNum++;
            }

            // Get the column container
            var column = containerTmp.find('.col-' + colNum);

            // Does the column exist? If not, its a new column and we'll need to create it
            if (column.length == 0)
            {
                column = $('<div class="col col-' + colNum + '"></div>');

                // Append column to container
                containerTmp.append(column);
            }

            // Keep track of widest ele in column, used for setting width of container
            if (eleWidth > colWidth)
            {
                colWidth = eleWidth;
            }

            column.width(colWidth);

            // Increment the calculated column height
            colHeight += eleHeight;

            // Append element to column
            column.append(ele); 
        });

        container.html(containerTmp.html());

        // Calculate container width
        container.children('.col').each(function(i, o)
        {
            containerWidth += $(o).width();
        });

        container.width(containerWidth);
    };
    </script>

</body>
</html>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...