You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让搜索结果宽度与HTML表格保持一致?

解决搜索结果表格宽度不一致问题

问题原因

表格默认采用auto布局,列宽会根据当前可见行的内容自动调整。搜索不同关键词时,显示内容的宽度差异会导致表格整体尺寸变化。

解决方案

1. 给表格设置固定布局

通过CSS强制表格使用固定布局,让宽度保持稳定:

table.table_brdr {
  table-layout: fixed;
  width: 100%; /* 也可指定固定像素值,比如800px */
  border-collapse: collapse; /* 可选,优化边框显示效果 */
}

table-layout: fixed会优先依据表头(<th>)的宽度分配列宽,不受后续行内容影响,确保表格宽度始终一致。

2. 修复HTML语法错误

原代码存在两处语法错误,会干扰表格正常渲染:

  • <th><strong>Column2</th> 缺少闭合标签 </strong>
  • <td>abctd <td> 闭合错误,应改为 </td>

3. 可选:自定义列宽(按需调整)

如果需要更精准的列宽控制,直接给表头添加宽度样式:

table.table_brdr th {
  background-color: #a6a6a6;
  color: black;
  width: 33%; /* 三列平均分配,也可使用固定像素值如200px */
}

修改后的完整代码

HTML

<p><input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search" title="Search"></p>
<table class="table_brdr" id="myTable">
  <tr>
    <th>Column1</th>
    <th><strong>Column2</strong></th>
    <th>Column3</th>
  </tr>

  <tr>
    <td></td>
    <td>xyz</td>
    <td>03/30/2017</td>
  </tr>

  <tr>
    <td>test12</td>
    <td>https://www.yahoo.com/ </td>
    <td>03/30/2017</td>
  </tr>

  <tr>
    <th>Column1</th>
    <th> New Column</th>
    <th>Column3</th>
  </tr>

  <tr>
    <td>John</td>
    <td>abctd </td>
    <td>09/30/2019</td>
  </tr>

  <tr>
    <th>Column1</th>
    <th> New Column2</th>
    <th>Column3</th>
  </tr>

  <tr>
    <td>Doe</td>
    <td>abctd </td>
    <td>06/30/2019</td>
  </tr>
</table>

CSS

table.table_brdr {
  table-layout: fixed;
  width: 100%;
  border-collapse: collapse;
}

table.table_brdr td {
  padding: 8px 10px;
  border: none;
  word-wrap: break-word; /* 可选,让长内容自动换行避免溢出 */
}

table.table_brdr th {
  background-color: #a6a6a6;
  color: black;
  width: 33%;
}

tr:nth-of-type(odd) {
  background-color: #D3D3D3; /* 修复原代码缺失的冒号 */
}

#myInput {
  background-image: url('/css/searchicon.png');
  background-position: 10px 10px;
  background-repeat: no-repeat;
  width: 20%;
  font-size: 16px;
  padding: 12px 20px 12px 40px;
  border: 1px solid #ddd;
  margin-bottom: 12px;
}

JS

function myFunction() {
  const userInput = document.getElementById("myInput").value.toUpperCase();
  const tableRows = document.querySelectorAll("table tr");
  for (let i = 0; i < tableRows.length; i++) {
    const rowTextContent = tableRows[i].innerText.toUpperCase();
    tableRows[i].style.display = rowTextContent.includes(userInput) ? "" : "none";
  }
}

内容的提问来源于stack exchange,提问作者magicsinger

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 14:24:19