如果文本溢出,如何在列中添加水平滚动条,否则它将被隐藏

how to add a horizontal scroll bar in column if the text overflows or else it'll be hidden

我想在列的文本溢出时向该列添加一个水平滚动条。我不想增加列宽。我使用了 nowrap 文本,但也想为其添加水平滚动条。如果文本没有溢出,则滚动条将被隐藏。这是我的代码。现在这个滚动条适用于整个列而不是任何特定列。对于这种情况,我必须使用 JS,但我不确定如何正确使用它。

HTML:

<table class="table">
   <thead>
     <tr>
      <th>Serial</th>
      <th>Name of the Project</th>
       <th>Name of the Clients</th>
      </tr>
  </thead>
  <tbody>  
   <tr class="active">                                                                             
    <td>1</td>

    <td>Column content</td>

    <td class="tHor">

      Name 1 Name 2

      Name 1 Name 2

      Name 1 Name 2

      Name 1 Name 2

    </td>

  </tr>
  <tr>

   <td>3</td>

   <td>Column content</td>

   <td class="tHor"> Name 1 Name 2</td>
  </tr>

 </tbody>
</table>

CSS:

.tHor{
   overflow-x: auto;
   white-space: nowrap;
}

我希望这个 'tHor' class 有一个滚动条,如果文本在此代码中增加,第一行的列将显示该条,但对于第二行,必须隐藏水平滚动条的列.

您不需要 JavaScript 即可实现。只需设置 max-width 属性:

.tHor{
  overflow-x: auto;
  white-space: nowrap;
  max-width: 200px;
}
<table class="table">
  <thead>
    <tr>
      <th>Serial</th>
      <th>Name of the Project</th>
      <th>Name of the Clients</th>
    </tr>
  </thead>
  <tbody>  
    <tr class="active">                                                             
      <td>1</td>
      <td>Column content</td>
      <td class="tHor">
        Name 1 Name 2
        Name 1 Name 2
        Name 1 Name 2
        Name 1 Name 2
      </td>

    </tr>
    <tr>
      <td>3</td>
      <td>Column content</td>
      <td class="tHor"> Name 1 Name 2</td>
    </tr>

  </tbody>
</table>