在宽度为1px的表格单元内进行过渡

时间:2017-03-07 13:58:40

标签: javascript html css

以下代码包含一个单元格内的过渡,其宽度为:1px,用于包装其内容。但是表格布局的变化发生在过渡的结束(或开始):

var animator = document.getElementById("animator");

function Animate(){
    if(animator.style.width === "100%"){
        animator.style.width = "0";
    }else{
        animator.style.width = "100%";
    }
}

document.getElementById("btn").addEventListener("click", Animate);
<table style="width:100%;">
<tr>
  <td style="width:1px;">
  <div id="animator" style="width:100%; overflow:hidden; transition:2s linear width;">
    <div style="background-color:red;">
  111
  </div>
    </div>
  </td>
  <td>1111111111111111</td>
  <td>11111111</td>
  <td style="width:1px;">11111111</td>
</tr>
</table>

<button id="btn">Animate
</button>

如何在转换过程中强制表格进行布局?

1 个答案:

答案 0 :(得分:1)

这是有效的。我操纵了包含表格单元格的maxWidth属性以动态更改大小。萎缩过程比成长过程更自然,但这是有效的。为了更普遍地进行增长过程,您可能需要克隆div并在动画时测量克隆的增长,并将该宽度应用于表格单元格。有关此版本,请参阅下面的jsfiddle。

<div id="info">Ready...</div>
<table style="width:100%;">
<tr>
  <td id="tdID" style="width:1px;">
  <div id="animator" style="width:100%; overflow:hidden; transition:2s linear width;">
    <div style="background-color:red;">
  111
  </div>
    </div>
  </td>
  <td>1111111111111111</td>
  <td>11111111</td>
  <td style="width:1px;">11111111</td>
</tr>
</table>

<button id="btn">Animate
</button>

<script>
var animator = document.getElementById("animator");
var tcell = document.getElementById("tdID");
var info = document.getElementById("info");
var t_start;
var max_width;

function shrink() {
  var d = new Date();
  var t = d.getTime();
  tcell.style.maxWidth = animator.offsetWidth + "px";
  if(t - t_start < 2000) 
    setTimeout(shrink,50);
  else
    info.innerHTML = "done";
}

function grow() {
  var d = new Date();
  var t = d.getTime();
  var pcnt = (t-t_start) / 1000;

  if(pcnt<1) {
    tcell.style.maxWidth = (max_width*pcnt) + "px";
    setTimeout(grow,50);
  }
  else {
    tcell.style.maxWidth = max_width + "px";
    info.innerHTML = "done.";  
  }
}


function Animate(){
  var d = new Date();
  t_start = d.getTime();

  info.innerHTML = "start...";
  if(animator.style.width === "100%") {
    animator.style.transition = "2s linear width";
    max_width = animator.offsetWidth; 
    animator.style.width = "0px";
    setTimeout(shrink,50);
  } else {
    animator.style.transition = "0s linear width";
    animator.style.width = "100%";
    setTimeout(grow,50);
  }
}

document.getElementById("btn").addEventListener("click", Animate);

https://jsfiddle.net/FrancisMacDougall/g2c5kcx9/