[英]Using JQuery to set CSS Keyframe
我正在嘗試確定div
的高度,該高度取決於文本的大小是動態的。 我試圖在CSS中將其動態設置為我的原始問題https://stackoverflow.com/questions/24150538/defining-a-height-in-css-for-animation-keyframe-within-itself?noredirect=1# comment37269329_24150538 。
我現在似乎在https://github.com/jQueryKeyframes/jQuery.Keyframes上有了一個JQuery,可以使您做到這一點。 因此,我遵循了他們的示例,並在我的CSS
文件中刪除了keyframe
,並將其包含在腳本中,如以下代碼片段所示:
<body>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="/pathToFile/jquery.keyframes.min.js"></script>
<div id="test"> hello</div>
<script>
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.
});
</script>
</body>
我的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(示例):
<div id="testcontainer">
<div id="test">hello</div>
</div>
CSS(示例):
#test {
position: absolute;
}
#testcontainer {
position: relative;
background: pink;
width: 300px;
height: 300px;
}
希望這會有所幫助。
我設法通過創建一個定義了關鍵幀名稱的類來實現激活關鍵幀
.add_keyframe{
animation: shrink 5s
}
然后使用jQuery添加它
$('#whatever').addClass('add_keyframe');
添加類后,您的關鍵幀應運行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.