CSS转换取决于样式分配的顺序

CSS transition depends on order of style assignments

本文关键字:顺序 分配 样式 转换 取决于 CSS      更新时间:2023-09-26

为了使一个包含文本的容器在添加新文本后逐渐扩展,我使用了css transition属性。准确地说,我固定了当前宽度,添加文本,然后释放宽度。JS代码如下:

footer.style['max-width'] = footer.offsetWidth + 'px'
footer.innerHTML += ' additional text'
footer.style['max-width'] = '500px'

用这个css为footer:

overflow: hidden;
text-overflow: clip;
white-space: nowrap;

这不起作用。为了找到解决方法,我添加了另一行代码:

footer.style['height'] = footer.offsetHeight + 'px'

现在,由于这一行被放在max-width的赋值之前(所以在代码段的开头(,它不起作用。但把它放在那一行之后(使它成为第二行(——确实如此。问题是为什么?处理转换的正确方法是什么?(但主要是为什么?(

Fiddle在firefox 40.0和chrome 39.0中测试:http://jsfiddle.net/53dbm6vz/

问题可能是两个footer.style['max-width']赋值都发生在同一同步操作中。浏览器可能会完全忽略中间值。

如果将操作拆分为两部分,则可以解决此问题:

  1. 设置初始化宽度和
  2. 使用setTimeout触发实际分配

尝试如下:

footer.style['max-width'] = footer.offsetWidth + 'px'
window.setTimeout(function() {
  footer.innerHTML += ' additional text'
  footer.style['max-width'] = '500px'
}, 0)