防止将 <td> 内容从文本动态更改为 <input> 元素以扩展列的宽度

Prevent dynamic change of <td> content from text to an <input> element from expanding the width of the column

我剪下了这个 Svelte(也可以在 Svelte repl here]

<script>
  const rows = 10
  const cols = 5
  let clickedRow = -1
  let clickedCol = -1

  function clicked(row, col) {
    clickedRow = row
    clickedCol = col
  }

  function clear() {
    clickedCol = -1
    clickedRow = -1
  }
</script>

<table>
    {#each Array(rows) as _, row}
        <tr>
            {#each Array(cols) as _, col}
                <td on:click={() => clicked(row, col)}>
                    {#if clickedRow === row && clickedCol === col}
                        <input type="text" value="Hello" />
                    {:else}
                        Hello {row}.{col}
                    {/if}
                </td>
            {/each}

        </tr>
    {/each}
</table>

<button on:click={clear}>Clear</button>

<style>
    table, tr, td {
        border: solid 1px
    }
</style>

当您单击 table 单元格时,它会切换到 <input> 元素,模拟编辑数据的能力。但是一旦添加了 <input> id,<td> 就会变宽,导致整个列变宽。这对用户来说是一种神经质的体验。

如何在不加宽列的情况下更改 <td> 的内容?

换句话说,一旦 table 的大小适合内容,如何保持每列的宽度固定,即使我更改了单元格的内容?

width: 0; min-width: 100%; 技巧可以帮到你。

input {
    width: 0;
    min-width: 100%;
    height: 0;
    min-height: 100%;
    margin: 0;
}

Repl