【问题标题】:What is the best way divide content between n columns?在 n 列之间划分内容的最佳方法是什么?
【发布时间】:2010-10-16 15:15:04
【问题描述】:

我读过这篇优秀的Multi-column list article,以及this question on SO。我得出的结论是,没有跨浏览器的方法可以将长的无序列表转换为 n 等长的列。到目前为止,我已经简化为这样的多 ul 解决方案:

//Three columns.
string col1 = string.Empty;
string col2 = string.Empty;
string col3 = string.Empty;
int currItem = 0;
int collectionCount = myItemCollection.Count;

foreach item in myItemCollection {
  currItem++;
  if (currItem < collectionCount * .33)
  {
    col1 = col1 + item.someProperty
  } 
  else if (currItem < collectionCount * .67)  
  {
    col2 = col2 + item.someProperty
  } 
  else
  {
    col3 = col3 + item.someProperty
  }
}

string allColumns = @"<ul>" + col1 + "</ul><ul>"
                      col2 + "</ul><ul>" + col3 + "</ul>";

Response.Write(allColumns);

有没有更简单的方法将我的列表分成三个一组,或者更好的是,当元素是“第三个”中的最后一项时,只需编写适当的结束/开始 ul 标记?

【问题讨论】:

    标签: c# asp.net html css


    【解决方案1】:

    这是我个人会选择的实现方式。

    const int numColumns = 3;
    const int numColumns = 3;
    var columnLength = (int)Math.Ceiling((double)myItemCollection.Count / 3);
    
    for (int i = 0; i < myItemCollection.Count; i++)
    {
        if (i % columnLength == 0)
        {
            if (i > 0)
                Response.Write("</ul>");
            Response.Write("<ul>");
        }
        Response.Write(myItemCollection[i].SomeProperty);
    }
    
    if (i % columnLength == 0)
        Response.Write("</ul>");
    

    你完全避免了字符串连接(当你只是写一个流时真的没有必要,如果你不是你想要xse StringBuilder)以及那些可能潜在的讨厌的浮点操作导致长列表不准确(至少它们是不必要的)。

    无论如何,希望对您有所帮助...

    【讨论】:

    • 优秀。通过一些小的清理,这段代码绝对完美。正是我所希望的。
    • 很高兴它为您解决了问题...(如果它包含任何错误,请告诉我,以便我对其进行编辑,否则我会假设您只是针对您自己的特定用途进行了一些小修改。 )
    【解决方案2】:

    这为时已晚,但 Response.Write 会在不可预知的地方输出,很可能在所有其他输出之前。

    “正确的”代码应该在 CreateChildren、Page_Load 或任何其他地方构建控件:

    List<string> items = new List<string>() { "aaa", "bbb", "ccc", "ddd", "eee" };
    int colSize = (int)Math.Ceiling(items.Count / 3.0);
    
    HtmlGenericControl ul = null;
    for (int i = 0; i < items.Count; i++)
    {
        if (i % colSize == 0)
        {
            ul = new HtmlGenericControl("ul");
            Page.Form.Controls.Add(ul);
        }
    
        HtmlGenericControl li = new HtmlGenericControl("li");
        li.InnerText = items[i];
        ul.Controls.Add(li);
    }
    

    这样您就不必担心呈现和跟踪打开/关闭标签。

    【讨论】:

      【解决方案3】:

      如果它是一个无序列表,你可以将

    • 向左浮动,并给它一个小于 (100 / n)% 的宽度
    • 【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-01-20
        • 2011-04-04
        • 2011-08-16
        • 1970-01-01
        • 2010-09-15
        • 2011-08-06
        • 1970-01-01
        相关资源
        最近更新 更多