【问题标题】:CSS Transition not working in table colgroupCSS 转换在表 colgroup 中不起作用
【发布时间】:2023-04-01 03:36:01
【问题描述】:

当 colgroup 宽度改变时,过渡不起作用。

$('#but').click(function() {
  if ($('table col').hasClass("expanded"))
    $('table col').removeClass('expanded');
  else
    $('table col').addClass('expanded');
});
table,
th,
td {
  border: 1px solid black;
}
table col {
  -webkit-transition: width .8s ease;
  -moz-transition: width .8s ease;
  -ms-transition: width .8s ease;
  -o-transition: width .8s ease;
  transition: width .8s ease;
}
.expanded {
  width: 200px
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<button id="but">Button</button>

<table>
  <colgroup>
    <col></col>
    <col></col>
  </colgroup>
  <tr>
    <th>Month</th>
    <th>Savings</th>
  </tr>
  <tr>
    <td>January</td>
    <td>$100</td>
  </tr>

</table>

我正在使用此代码。在此代码中,CSS 过渡属性将不起作用。 transition: width .8s ease;

【问题讨论】:

标签: javascript jquery css css-transitions


【解决方案1】:

CSS 过渡需要能够计算起点和终点之间的差异才能过渡它。如果未指定宽度,则宽度将默认为 auto,从 auto 开始,您无法将动画设置为像 200px 这样的固定值,因为 auto 可以是任何值。

将基本的width 属性应用到默认值为100pxtable col 选择器可以解决问题,因为现在浏览器可以理解您想要做什么。

$('#but').click(function() {
  if ($('table col').hasClass("expanded"))
    $('table col').removeClass('expanded');
  else
    $('table col').addClass('expanded');
});
table,
th,
td {
  border: 1px solid black;
}
table col {
  width: 100px;
  -webkit-transition: width .8s ease;
  -moz-transition: width .8s ease;
  -ms-transition: width .8s ease;
  -o-transition: width .8s ease;
  transition: width .8s ease;
}
.expanded {
  width: 200px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<button id="but">Button</button>

<table>
  <colgroup>
    <col></col>
    <col></col>
  </colgroup>
  <tr>
    <th>Month</th>
    <th>Savings</th>
  </tr>
  <tr>
    <td>January</td>
    <td>$100</td>
  </tr>

</table>

【讨论】:

    【解决方案2】:

    一个简单的解决方法是使用min-width 属性。

    由于转换需要一个固定值才能工作,因此将width: 0px;min-width: auto; 赋予您的元素,并且因为min-width 属性比width 更重要,所以您的元素看起来相同,并且您的转换顺利运行。

    table col {
        min-width: auto;
        width: 0px;
        -webkit-transition: width .8s ease-in-out;
        -moz-transition: width .8s ease-in-out;
        -ms-transition: width .8s ease-in-out;
        -o-transition: width .8s ease-in-out;
        transition: width .8s ease-in-out;
    }
    

    看到这个fiddle

    【讨论】:

    • 你的意思是完全不设置宽度吗?或者没有将宽度专门设置为&lt;colgroup&gt;
    • 这里实际上不需要 标签。例如,您可以在 标签上应用过渡。查看更新的小提琴:jsfiddle.net/5vff7yyu/2
    • 实际上我正在动态更改宽度,这就是为什么我使用 colgroup..so only..需要解决方案而不在 colgroup 中设置宽度
    • 如果您需要更多帮助,您需要在此处提供更详细的示例!
    • 感谢这个解决方案,大量 +1 用于详细说明 widthmin-width,这确实是一个巧妙的技巧,我想知道它是如何跨浏览器的 :)
    猜你喜欢
    相关资源
    最近更新 更多
    热门标签