javascript - 具有多列的 CSS 列表,具有水平滚动和自动列宽和高度

标签 javascript html css list listview

我有一个自动生成的列表(元素的数量和它们的宽度事先不知道):

<div>Page header</div>
<div>
  <ul>
    <li>One</li>
    <li>Two</li>
    <li>Three</li>
    ...
    <li>Ninety nine</li>
    <li>One hundred</li>
  </ul>
</div>
<div>Page footer</div>

我想要以下布局:

+-----------------------------------------+
| Page header                             |
|                                         |
| +-------------------------------------+ |
| |One    Five   Nine    Thirteen  .... | |
| |Two    Six    Ten     Fourteen  .... | |
| |Three  Seven  Eleven  Fifteen   Ninet| |
| |Four   Eight  Twelve  Sixteen   One h| |
| <[=======scrollbar=========]----------> |
|                                         |
| Page footer                             |
+-----------------------------------------+ <-- window (viewport) frame

这样

  • 列表填充窗口宽度和窗口高度(页眉和页脚高度除外)并在窗口调整大小时自动调整大小,
  • 列表水平滚动,带有水平滚动条,
  • 自动选择行数和列数,
  • 列的宽度由列表中最宽的元素自动选择,或者甚至可能自动为每列自动选择为该列的最宽元素。

我知道如何针对固定的列数进行类似的设计,但不会针对自动调整屏幕区域的列数进行设计。

如果解决方案不是微不足道的,也许有现成的 .css 或 .js 可以做到这一点?

最佳答案

我想这就是您要找的一切。它主要使用 JQuery 来实现效果(其中一些在 CSS 中)。它也是动态的,因此它应该处理您拥有的任何数量的 li。我在下面的代码中解释了它是如何工作的:

//find the number of li's
var numberOfResults = $('li').length;

//set how many li's you want per row
var numberPerRow = 4;

//pull the first ul for later use
var $firstUL = $('ul');

//divide the number of li's from the number you want per row then round the number
var numberOfRows = Math.ceil(numberOfResults/numberPerRow);

//find the width of the largest li for later use
var maxWidth = Math.max.apply( null, $( 'li' ).map( function () {
  return $( this ).outerWidth( true );
}).get() );

//set container width the width of all rows * the width of each one
$(".container").css({"width": (maxWidth*numberOfRows)+"px"})

//add a ul depending on the number of rows
for(var i=1;i<=numberOfRows;i++){
   $(".container").append('<ul></ul>');
}

// go through each row and add the lis
for(var i=1;i<=numberOfRows;i++){
   $firstUL.find('li:lt('+(numberPerRow)+')').appendTo('ul:eq('+(i)+')');      
}

//loop through all of the lis and set the width to the max
$("li").each(function(){
   $(this).css({"width":maxWidth+"px"})
});

FIDDLE

关于javascript - 具有多列的 CSS 列表,具有水平滚动和自动列宽和高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27750600/

相关文章:

javascript - jQuery:悬停时隐藏div,点击时保持可见

javascript - 为什么代码中的 catch 语句没有捕获 async 函数中的错误?

html - 在html中绘制特定的线条

javascript - 为什么在将对象插入数组后 indexOf 不起作用

html - 基于 Angular 4的下拉列表进行过滤

html - 如何使所有照片正常显示?

javascript - 点击功能的问题

javascript - 如何将图像(在 Canvas 后面)推到前面以使其 onclick 功能起作用

javascript - 在 HTML5 Ipad 应用程序中捕获滑动效果以导航到下一页

javascript - &lt;textarea&gt; 占位符的换行符\n 在 Safari 上被忽略