【问题标题】:Is it possible to use CSS transition of width on a column depending on the content of a table cell?是否可以根据表格单元格的内容在列上使用 CSS 宽度转换?
【发布时间】:2020-07-20 22:25:40
【问题描述】:

我的目标是让表格的标题在您将鼠标悬停在标题单元格上时平滑地展开(使用 CSS transition)到单元格内容的全文宽度。我目前的方法是在标题单元格中设置文本容器的固定ch 宽度,并让该容器在悬停时扩展为100% 或固定的像素宽度。

这样做的实际原因是我正在使用的表格的可用宽度非常有限,这是一种在不删除列的情况下缩小整体宽度的方法。与悬停时弹出工具提示相比,这种显示全文的方式将是在标题中显示全文的一种更好的方式。

我希望列中所有单元格的宽度能够平滑过渡到新的标题单元格宽度。目前,唯一平滑扩展的元素是悬停在标题单元格中的扩展容器,并且列中的实际单元格扩展而没有过渡到新的计算宽度。

我见过其他示例(如thisthis),其中人们为宽度设置动画,但似乎没有人将宽度设置为由标题单元格内容设置的动态宽度。没有js可以吗?

工作示例:

* {
  box-sizing: border-box;
  transition: width 250ms ease-out;
  white-space: nowrap;
}

table {
  border-collapse: collapse;
  border-spacing: 0;
}

th:hover .th-title {
  width: 100% !important;
}

th,
td {
  width: 100%;
}

.th-title {
  overflow: hidden;
}

#th-domain {
  width: 3ch;
}

#th-name {
  width: 4ch;
}

#th-key {
  width: 3ch;
}

#th-protocol {
  width: 4ch;
}

#th-ip {
  width: 7ch;
}

/* Styling code */
th,
td {
  font-family: Monaco, monospace;
  padding: 4px 8px;
}

th {
  color: #fff;
  background-color: #1d7490;
  height: 32px;
}

tbody>tr {
  border-bottom: 1px solid #bfbfbf;
}
<table>
  <thead>
    <tr>
      <th>
        <div id="th-domain" class="th-title">DomainDomain</div>
      </th>
      <th>
        <div id="th-name" class="th-title">NameName</div>
      </th>
      <th>
        <div id="th-key" class="th-title">KeyKey</div>
      </th>
      <th>
        <div id="th-protocol" class="th-title">ProtocolProtocol</div>
      </th>
      <th>
        <div id="th-ip" class="th-title">Last IPLast IP</div>
      </th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><label>Domain1</label></td>
      <td><label>Name1</label></td>
      <td><label>Key1</label></td>
      <td><label>Protocol1</label></td>
      <td><label>IP1</label></td>
    </tr>
    <tr>
      <td><label>Domain2</label></td>
      <td><label>Name2</label></td>
      <td><label>Key2</label></td>
      <td><label>Protocol2</label></td>
      <td><label>IP2</label></td>
    </tr>
    <tr>
      <td><label>Domain3</label></td>
      <td><label>Name3</label></td>
      <td><label>Key3</label></td>
      <td><label>Protocol3</label></td>
      <td><label>IP3</label></td>
    </tr>
    <tr>
      <td><label>Domain4</label></td>
      <td><label>Name4</label></td>
      <td><label>Key4</label></td>
      <td><label>Protocol4</label></td>
      <td><label>IP4</label></td>
    </tr>
  </tbody>
</table>

编辑:调整表格宽度

【问题讨论】:

    标签: html css html-table css-transitions


    【解决方案1】:

    我没有找到用 css 做的好方法,但用 js 做起来很容易。我决定使用 mouseenter 和 mouseleave 事件来触发目标元素上的宽度动画,使用 anime.js 库,这在动画 css 属性时非常容易使用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-01-13
      • 2021-10-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-17
      • 1970-01-01
      相关资源
      最近更新 更多