简体   繁体   English

如何设置css3动画内联或通过javascript?

[英]How to set css3 animation inline or by javascript?

I'd like to set css3 animation effect to multi element, but the animated position was related to the count of elements which is not certain. 我想将css3动画效果设置为多元素,但是动画位置与不确定的元素数量有关。 I had to set css style by js (maybe a mvvm framework). 我必须通过js(可能是mvvm框架)设置CSS样式。

sample code: 样例代码:

@-webkit-keyframes position {
    0% {left:0}
    100% {left: 5*elementCounts px;}
}

I found there's no way to set css property by data-*, neither to add inline css3 animation defining inline. 我发现无法通过data- *设置css属性,也无法添加定义内联的内联css3动画。 Anybody have idea to resolve this in css or mvvm way? 有人有想法以CSS或mvvm的方式解决此问题吗?

Two options: 两种选择:

  1. If the number of possible ending positions is small and/or known in advance, you could write a number of variants of your keyframe definition with different names ( position10 , position20 , etc). 如果可能的结束位置数量很少和/或事先已知,则可以使用不同的名称( position10position20等)编写关键帧定义的多个变体。

  2. If that is not an option, consider setting the element's position with jQuery so you can do all the calculations you need, and only relying on CSS for the animation duration. 如果不是这样,请考虑使用jQuery设置元素的位置,以便您可以进行所有需要的计算,并且仅在动画持续时间内依靠CSS。 Here's a fiddle showing how you can achieve that: 这是显示您如何实现的小提琴

JS JS

$(document).ready(function() {
    // calculate the intended location
    var div1Position = 100*1;
    var div2Position = 100*2;

    $('#div1').animate({ left: div1Position });
    $('#div2').animate({ left: div2Position });
});

HTML HTML

<div id="parent">
    <div id="div1" class="box">Test #1</div>
    <div id="div2" class="box">Test #2</div>
</div>

CSS CSS

#parent {
    position: relative;
}

.box {
    background-color: grey;
    color: red;
    position: absolute;
    display: block;
    height: 75px;
    width: 75px;
    -webkit-transition: 1s ease-in-out;
    -moz-transition: 1s ease-in-out;
    -o-transition: 1s ease-in-out;
    transition: 1s ease-in-out;
}

Hope this helps! 希望这可以帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM