【问题标题】:How to stop a cell's content from being used to calculate column width如何阻止单元格的内容被用于计算列宽
【发布时间】:2015-09-22 17:18:08
【问题描述】:

我有一个动态宽度的表格,每列都是该宽度的动态部分,具体取决于单元格内容。

在该表的标题中,我有一个设置为 100% 宽度的输入,它最初是隐藏的。触发时,会出现输入。不幸的是,如果列的单元格内容很窄,那么列宽会被重新计算并且宽度会跳跃。

如何将输入设置为仅填充单元格的宽度而不将其推宽?

我不相信有解决方案,但我想在放弃之前我会询问更大的社区。我的猜测是我不能没有硬编码宽度,但这是不可能的。

编辑: 我的解决方案是让浏览器进行单元格宽度计算,然后使用 Javascript 将列宽显式设置为计算出的任何值。这允许单元格内容确定宽度,但我仍然得到设置宽度的行为。

function toggleInput(){
  var target = document.querySelector('.hidden')
  var newStyle = (target.style.display == 'block') ? 'none' : 'block';
  document.querySelector('.hidden').style.display = newStyle;
}

document.querySelector('th').addEventListener('click',toggleInput);
table,td,th{
  border:1px solid red;
}
*{
  box-sizing:border-box;
}

table,
input{
  width:100%;
}

.hidden{
  display:none;
}
<table>
  <thead>
    <tr>
      <th>
        Click me
        <div class="hidden">
          <input />
        </div>
      </th>
      <th>
      </th>
      <th>
      </th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>
        Blah
      </td>
      <td>
        Some longer text to stretch
      </td>
      <td>
        More text
      </td>
  </tbody>
</table>

【问题讨论】:

  • 您可以在TH中手动设置列的宽度。
  • 我猜我不能没有硬编码宽度,但这是不可能的。

标签: javascript html css


【解决方案1】:

通过使用以下 CSS:

table { table-layout:fixed }

您的修复代码:

function toggleInput(){
  var target = document.querySelector('.hidden')
  var newStyle = (target.style.display == 'block') ? 'none' : 'block';
  document.querySelector('.hidden').style.display = newStyle;
}

document.querySelector('th').addEventListener('click',toggleInput);
table,td,th{
  border:1px solid red;
}
*{
  box-sizing:border-box;
}

table,
input{
  width:100%;
}

table { table-layout:fixed; }

.hidden{
  display:none;
}
<table>
  <thead>
    <tr>
      <th>
        Click me
        <div class="hidden">
          <input />
        </div>
      </th>
      <th>
      </th>
      <th>
      </th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>
        Blah
      </td>
      <td>
        Some longer text to stretch
      </td>
      <td>
        More text
      </td>
  </tbody>
</table>

【讨论】:

  • 不完全。来自 MDN:“表格和列的宽度由表格和列元素的宽度或第一行单元格的宽度设置。后续行中的单元格不影响列宽。”我需要由每列内容确定的列。
  • @Pickle - 如果不设置固定宽度是不可能的。
猜你喜欢
  • 2011-03-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-17
  • 1970-01-01
  • 2015-12-14
  • 1970-01-01
相关资源
最近更新 更多