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

标签 javascript html css scrollbar horizontal-scrolling

如果列的文本溢出,我想向该列添加一个水平滚动条。我不想增加列宽。我使用了 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”类有一个滚动条,第一行的列将显示该条,但对于第二行,必须隐藏水平滚动条的列。

最佳答案

您不需要 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>

关于javascript - 如果文本溢出,如何在列中添加水平滚动条,否则它将被隐藏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51054507/

相关文章:

javascript - 如何从 Handlebars 文件(.hbs)在Angularjs Controller 中传递参数?

css - 在无序列表旁边剩余的宽度上跨越 div?

javascript - 将 Webpack 与 React-router bundle.js 一起使用未找到

Java JLabel HTML 在字体与系统字体冲突时显示乱码

http-equiv 上的 Javascript Hook ="refresh"

javascript - 使用 Div 水平和垂直填充空间

html - margin :auto and justify-content/align-items center?有什么区别

javascript - document.load 中是否应用了所有 CSS?

javascript - 如何使用 fetch API 的响应正文将一些数据从服务器发送回浏览器

javascript - window.open() 已处于全屏模式时出现问题