允许html表调整大小而不使硬编码大小大于页面宽度

时间:2018-03-28 10:24:46

标签: javascript html html-table

我有一些Javascript代码允许调整表格列的大小,问题是如果我使列更宽并且表格已经使用了100%的页面,它将通过缩小其他列来实现列扩展。

https://jsfiddle.net/paultaylor/v12x963o/22/

我想要它做的只是使该列更宽并使其他列保持相同,这通常意味着需要一个水平滚动条,这很好。

但我似乎能做的唯一方法是在开始时将表格宽度设置为比屏幕尺寸更宽,即将表格样式设置为宽度:2000px

但是这意味着滚动条从一开始就存在,默认情况下我希望表适合屏幕,如果用户调整大小,只能比屏幕更宽,我将表格宽度设置为2000px是一个任意值。

我尝试制作表格样式display: flex;flex-wrap: nowrap; 但它没有效果

注意 建议的重复问题是要求一种方法来调整表格列的大小,这个问题使用了该解决方案但是询问了一个特定的问题,即如何允许表格宽度大于屏幕宽度,以便允许使列更大而不使另一个更小补偿

1 个答案:

答案 0 :(得分:0)

如果没有表格元素,则让元素超出页面宽度会更简单。

我建议用JSON定义表数据,然后从这些数据中以编程方式生成html。

此代码只是超出页面宽度。

const cols = getCols(4);//array of the col-n elements
function getCols(nCols){
  const arr = [];
  for(let i=0;i<nCols;i++){
    arr.push(document.getElementById(`col-${i}`));
  }
  return arr;
}
//use custom code on cols as you already have to change their widths.
//probably better to ignore the left side of the first column and the right side of the last column.
//decide how to handle the right column width considering you cannot drag beyond the page width.
/*
e.g.
on drag check mouse x distance to element.right, if within range (e.g. 8 px), set element.width to distance of element.left from mouse x.
*/
#container {
  white-space: nowrap;
  overflow: auto;
}
.col {
  display: inline-block;
}
input[type="text"] {
  width: 30ch;
  display: block;
}
<!-- this should be generated with javascript with the table data as a JSON object -->
<div id="container">
  <div id="col-0" class="col">
    <div id="header-0"> Header 0 </div>
    <input id="input-0-0" value="input 0.0" type="text">
    <input id="input-0-1" value="input 0.1" type="text">
  </div>
  <div id="col-1" class="col">
    <div id="header-1"> Header 1 </div>
    <input id="input-1-0" value="input 1.0" type="text">
    <input id="input-1-1" value="input 1.1" type="text">
  </div>
  <div id="col-2" class="col">
    <div id="header-2"> Header 2 </div>
    <input id="input-2-0" value="input 2.0" type="text">
    <input id="input-2-1" value="input 2.1" type="text">
  </div>
  <div id="col-3" class="col">
    <div id="header-3"> Header 3 </div>
    <input id="input-3-0" value="input 3.0" type="text">
    <input id="input-3-1" value="input 3.1" type="text">
  </div>
</div>