【问题标题】:css3 animation and discrepancy between style and computed stylecss3动画以及样式和计算样式之间的差异
【发布时间】:2012-11-23 04:05:19
【问题描述】:

我正在研究 css3 动画,我偶然发现了 animation-fill-mode 属性,它 基本上可以在动画结束后将动画的值应用到元素上。

默认情况下,当动画结束时,元素会恢复到原来的状态。

例如

 #box{
     width: 100px;
     position: absolute;
 }

#box.startAnimation{

    animation-name:first, second;
    animation-duration:5s, 5s;
    animation-timing-function:linear;
    animation-delay:0s, 5s;
    animation-iteration-count:1;
    animation-fill-mode:forwards;
}

@-moz-keyframes first
{
    0%   {left:40%; top:0px;background:cyan}
    100% {left:100px; top:0px;}
}

@-moz-keyframes second
{
     0%   {left:100px; top:0px;}
     100% {left:0px; top:300px;width:300px}
}

forwards animation-fill-mode 将使应用了 startAnimation 类的元素宽度为 300 像素,顶部为 300 像素,左侧为 0 像素。

但是,这些值应用于元素的计算样式,而不是 css 样式。

这可能会导致不一致,因为如果有人现在尝试获取元素的宽度,他会得到 100 像素而不是 300 像素。

在大型项目中,上述情况确实会变得很奇怪,在这些项目中制作动画并且需要访问宽度、高度、左侧等属性的 javascript 逻辑。

我的意思是计算样式与您通过 div.style.width 读取的样式之间存在这种差异(例如)

我很想听听上述问题的意见或解决方案

问候

【问题讨论】:

    标签: css animation


    【解决方案1】:

    我认为这取决于您要完成的工作。您是否有要解决的问题的更具体用例,然后我可能会得到更具体的答案。

    在上述情况下,我不会使用关键帧。在大多数项目中,我发现我不需要关键帧,除非我正在制作某种高级动画,比如一个人走路之类的。对于大多数 Web 界面,转换和类更改似乎都可以正常工作。

    我将有一个基类和一个转换类,并使用 javascript 添加转换类。然后状态将保持并保持一致,因为它来自您添加的类,而不是来自关键帧的末尾。

    .base-class { width: 100px; left: 0; top: 0; -webkit-transition: 1s all; }
    .transition-class { width: 300px; -webkit-transform: translateX(300px); }
    
    $('.base-class').on('click', function(){ $(this).addClass('transition-class'); });
    

    如果需要也可以使用JS查找动画的结尾

    $('.base-class').on('-webkit-transition-end', function(){
        var width = $(this).width();
        alert(width);
    })
    

    (我也会使用 translateX 而不是 left。它会快一点)

    【讨论】:

      猜你喜欢
      • 2012-10-28
      • 2013-11-28
      • 2018-02-13
      • 2012-12-11
      • 2022-11-30
      • 2013-07-02
      • 2023-04-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多