使所有表的列具有与第一个表相同的宽度

时间:2015-06-28 15:11:37

标签: javascript jquery css html5 jquery-mobile

我正在开发一个HTML5 / jQuery Mobile / PHP网站。该网站有多个单独的表,因为我决定在多个页面(<div data-role="page">)中分解数据。这些页面填充了电影信息(导演,年份,标题),但这是无关紧要的。

当用户单击其中一个标题时,表格将使用jQuery脚本按升序或降序排序。最初,当页面加载时,用户只能看到第一页(第一个表),如下图所示。用户可以通过单击按钮并向左或向右滑动来浏览页面,从而查看其他所有具有各自尺寸的表格。

enter image description here

如果用户点击 director 标题,则表格将由导演排序。但是,随着数据的变化,列的宽度也会发生变化。

我可以将列的宽度定义为某个固定宽度,但在这种情况下,由于用户可以定义可见的列,因此无法实现:例如,他可以创建新列 writer ,或者甚至关闭 director 列,在这种情况下,固定宽度不能正常工作。

我的问题是,我是否可以使其他表格的列宽度与第一个表格中的相同(或者为了概括而在其他表格中)?如果可以,是否有任何解决方案不依赖于javascript?

网站的基本结构:

<body>
    <div data-role="page" id="page-1">
        <table>...</table>
    </div>
    <div data-role="page" id="page-2">
        <table>...</table>
    </div>
    <div data-role="page" id="page-3">
        <table>...</table>
    </div>
    ...
</body>

1 个答案:

答案 0 :(得分:2)

由于我不知道您的任何JavaScript,因此您必须相应地替换变量/数组。

遍历每个页面,获取该页面上列的宽度。保存该列的最大宽度(跨页)

每页:

var colWidths = [];
for(var i=0, j=NumberOfPages; i<j; i++){
    for(var k=0, l=NumberOfColumns; k<l; k++){
        // check if the column is wider than the widest column for the previous pages
        if(colWidths[k]===undefined || colWidths[k] < $(...).width() ){
           // if so, change the widest width for that specific column to the current width
           colWidths[k] = $(...).width();
        }
    }
}

注意:将$(...)替换为表列的元素。您只需要从每个页面获取1个表列,因为在表中所有列的宽度都相同。

然后,因为您希望最终所有内容都等于100%,您需要找到每列的总数百分比。

var totalpx = 0;
// get combined widths of all the widest columns
for(var i=0, j=colWidths.length; i<j; i++){
    totalpx += colWidths[i];
}

// get percentage for each width from total
var percentages = [];
for(var i=0, j=colWidths.length; i<j; i++){
    percentages.push(colWidths[i]/totalpx);
}

然后,从百分比数组中为每列提供适当的百分比。

.width = percentages[i]