思路和实现方法都很简单,只是用的api很少有同学知道。这里记录下来。
1 function getKeyframes(name){ 2 var animation={} 3 var styleSheets=document.styleSheets 4 for(var i=0;i<styleSheets.length;i++){ 5 var item=styleSheets[i]; 6 if(item.cssRules[0] && item.cssRules[0].name && item.cssRules[0].name==name){ 7 animation.cssRule=item.cssRules[0]; 8 animation.styleSheet=item; 9 animation.index=0; 10 } 11 } 12 return animation; 13 }
1 //原生js操作keyframes值 2 var testDemo=document.getElementById(‘testDemo‘); 3 testDemo.onclick=function(){ 4 var arr=[ 5 {x:0,y:0}, 6 {x:-16.91,y:-32.36}, 7 {x:-29.76,y:-55.91}, 8 {x:-41.19,y:-72.73}, 9 {x:-52.00,y:-80.00}, 10 {x:-61.38,y:-68.68}, 11 {x:-67.30,y:-52.70}, 12 {x:-72.79,y:-33.13}, 13 {x:-78.12,y:-11.13}, 14 {x:-84.00,y:12.00} 15 ]; 16 var token = window.WebKitCSSKeyframesRule? ‘-webkit-‘:‘‘; 17 let key_name=‘testDemo‘ 18 var nameRule=getKeyframes(key_name); 19 var rules=‘@‘+token+‘keyframes ‘+key_name+‘{‘; 20 for(var i=0;i<arr.length;i++){ 21 rules+=(i+1)*10+‘%{transform:translate3d(‘+arr[i].x+‘px,‘+arr[i].y+‘px,0);opacity:‘+(i+1)*10/100+‘;}‘ 22 } 23 rules+=‘}‘; 24 if(JSON.stringify(nameRule)==‘{}‘){ 25 var sheet=document.styleSheets[0]; 26 // console.log(‘````‘,rules); 27 sheet.insertRule(rules,0); 28 }else{ 29 nameRule.styleSheet.deleteRule(nameRule.index) 30 nameRule.styleSheet.insertRule(rules,nameRule.index) 31 } 32 testDemo.style.animation=key_name+‘ 2s infinite‘; 33 }
原文:https://www.cnblogs.com/cm1236/p/13927280.html