使用JQuery设置CSS关键帧

我正在尝试根据文本的大小确定动态div的高度。 我试图在CSS中动态设置它作为我的原始问题https://stackoverflow.com/questions/24150538/defining-a-height-in-css-for-animation-keyframe-within-itself?noredirect=1# comment37269329_24150538 。

我现在看来有一个JQuery可以让你在https://github.com/jQueryKeyframes/jQuery.Keyframes上这样做。 所以我按照他们的示例删除了CSS文件中的keyframe ,并将其包含在脚本中,如下面的代码片段所示:

    
hello
var supportedFlag = $.keyframe.isSupported(); $.keyframe.define([{ name: 'myfirst', '0%': {top:$("#test").innerHeight()*-1; left:0px}, '50%': {top:100%; left:0px}, '100%': {top:$("#test").innerHeight()*-1; left:0px} }]); $(selector).playKeyframe({ name: 'myfirst', // name of the keyframe you want to bind to the selected element duration: 90, // [optional, default: 0, in ms] how long you want it to last in milliseconds timingFunction: 'linear', // [optional, default: ease] specifies the speed curve of the animation delay: 0, //[optional, default: 0, in ms] how long you want to wait before the animation starts in milliseconds, default value is 0 repeat: 'infinite', //[optional, default:1] how many times you want the animation to repeat, default value is 1 direction: 'alternate', //[optional, default: 'normal'] which direction you want the frames to flow, default value is normal fillMode: 'running', //[optional, default: 'forward'] how to apply the styles outside the animation time, default value is forwards complete: function(){} //[optional] Function fired after the animation is complete. If repeat is infinite, the function will be fired every time the animation is restarted. });

我的CSS:

 #test{ height: auto; width: 100%; position: relative; } 

我想知道为什么这不起作用。

SyntaxError是由您的分号分隔的javascript对象引起的:

 '0%': {top:$("#test").innerHeight()*-1; left:0px}, '50%': {top:100%; left:0px}, '100%': {top:$("#test").innerHeight()*-1; left:0px} 

用对象内的逗号替换分号:

 '0%': {top:$("#test").innerHeight()*-1, left:0}, '50%': {top:"100%", left:0}, '100%': {top:$("#test").innerHeight()*-1, left:0} 

这将修复语法错误。

编辑:此外, left的值需要从0px更改为0"0px" ,因为0px本身不是有效的语法。

编辑2:我用这个http://jsfiddle.net/7P9yY/2/玩了一下,让它接近我相信你问的问题。

关键帧定义为:

 $.keyframe.define([{ name: 'myfirst', '0%': {top:"0px"}, '50%': {top:$("#testcontainer").innerHeight() + "px"}, '100%': {top:"0px"} }]); 

此关键帧定义从页面顶部开始的动作(如果需要,可以将其更改为div的顶部),向下到底部,然后返回到顶部。 使用以下命令触发动画

 $("#test").playKeyframe({ name: 'myfirst', duration: 2000 }); 

HTML(示例):

 
hello

CSS(示例):

 #test { position: absolute; } #testcontainer { position: relative; background: pink; width: 300px; height: 300px; } 

希望这有点帮助。

我设法通过创建一个定义了关键帧名称的类来实现激活关键帧

 .add_keyframe{ animation: shrink 5s } 

然后使用jquery添加它

 $('#whatever').addClass('add_keyframe'); 

添加类后,您的关键帧应该运行。