模仿jquery,使用简单,自动添加浏览器前缀
var keyframes = new SHBKerframes();
keyframes.define([{
name:'myAnimate',
0%:{width:100px;height:100px;transform:scale(1);}
100%:{width:100px;height:100px;transform:scale(2);}
}]);
源码:
/**
*简单的SHBKerframes
*@author:索洪波
*@qq:609690891
*@version:1.0
*/
/**
*@SHBKerframes
*/ function SHBKerframes(){
this.prefix = '' ;
this.jsPrefix = '' ;
this.styleTag = null ; this.init();
this.createStyleTag();
}
SHBKerframes.prototype.init = function(){
var domPrefixes = ['webkit', 'Moz', 'O', 'ms', 'Khtml'];
var style = document.body.style ;
if(style.animationName !== undefined) return false;
for(var i = 0 ;i < domPrefixes.length ; i ++){
if(style[domPrefixes[i]+"AnimationName"] !== undefined){
this.animationName = domPrefixes[i] + 'Animation' ;
this.prefix = '-'+domPrefixes[i].toLowerCase() + '-' ;
this.jsPrefix = domPrefixes[i] ;
}
}
}
SHBKerframes.prototype.createStyleTag = function(css){
var style = document.getElementById('SHBKeyframes') ;
if(!style){
style = document.createElement('style') ;
style.id = 'SHBKeyframes' ;
style.type = 'text/css' ;
document.head.appendChild(style);
}
this.styleTag = style ;
}
SHBKerframes.prototype.createKeyframes = function(keyframe){
var style = document.body.style ;
var frameName = keyframe.name ;
var css = "" ;
css = '@'+this.prefix+'keyframes '+frameName +"{\n" ;
for(var key in keyframe){
if(key == 'name')continue;
css = css + key + '{' ;
for(var attr in keyframe[key]){
var jsAttr = attr.toString().replace(/-(\w)/g,function(){return arguments[1].toUpperCase();})
if(style[this.jsPrefix+jsAttr.charAt(0).toUpperCase()+jsAttr.substr(1)] !== undefined){
css = css + this.prefix + attr + ':' + keyframe[key][attr] +';';
}else{
css = css + attr + ':' + keyframe[key][attr] +';';
}
}
css += '}\n' ;
}
css += '}\n' ;
this.styleTag.appendChild(document.createTextNode(css));
}
SHBKerframes.prototype.define = function(list){
for(var i = 0 ; i < list.length ; i++){
this.createKeyframes(list[i]);
}
}