在表中添加时,转换不在toggleclass中工作

时间:2016-03-13 15:10:23

标签: javascript jquery html css

<style>
    table,
    th,
    td {
        border: 1px solid black;
    }
    .expanded {
        width: 200px
    }
</style>

<body>

    <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>


<script>
    $('#but').click(function(){
       if($('table col').hasClass("expanded"))
          $('table col').toggleClass('expanded',1000,"easeOutSine");
       else
         $('table col').toggleClass('expanded',1000,"easeOutSine");
    });
</script>
  

在上面的示例中,转换在添加切换类时不起作用   在jquery in table.please帮助我如何做到这一点。请不要改变   结构

Fiddle Link

1 个答案:

答案 0 :(得分:0)

您必须先设置一个设置宽度,例如:JSFiddle

table col {
    width: 75px; /* added this */
    -webkit-transition:width .8s ease;
    ...

或者,您可以使用jQuery的animate()来更改宽度,在这种情况下,您将删除css过渡:JSFiddle

if ($col.hasClass("expanded")) {
    $col.removeClass('expanded');
    $col.animate({"width": ""}, "slow");
} else {
    $('table col').addClass('expanded');
    $col.animate({"width": "200px"}, "slow");
}

至于使用toggleClass进行编辑,部分原因是因为你没有使用jQueryUI ...另一部分似乎是它不能用于col。如果我在表格上添加宽度,请参阅here ...或td上应该具有相同效果的广告,请参阅here