代码(因为使用到了最新的html5 api 所以不兼容低版本ie和其它一些不支持classList DOMList接口的现代浏览器)
(function(win){
function classList(e){
if(e.classList){
return e.classList;
}
else return new CSSClassList(e);
}
function CSSClassList(e){
this.e = e;
}
CSSClassList.prototype.contains=function(c){
if(c.length ===0 || c.indexOf(' ')!==-1){
throw new Error("invalid class name: '"+c+"'");
}
var classes = this.e.className;
if(!classes) return false;
if(classes === c) return true;
return classes.search('\\b'+c+'\\b') !== -1;
};
CSSClassList.prototype.add = function(c){
if(this.contains(c)) return;
var classes = this.e.className;
if(classes && classes[classes.length-1] !== ' '){
c = ' '+c;
}
this.e.className +=c;
};
CSSClassList.prototype.remove =function(c){
if(!this.contains(c))return;
var pattern = new RegExp('\\b'+c+'\\b\\s*','g');
this.e.className = this.e.className.replace(pattern,'');
};
CSSClassList.prototype.toggle=function(c){
if(this.contains(c)){
this.remove(c);
return false;
}else{
this.add(c);
return true;
}
};
CSSClassList.prototype.toString = function(){
return this.e.className;
};
CSSClassList.prototype.toArray = function(){
return this.e.className.match(/\b\w+\b/g) || [];
}
function $(query){
return document.querySelector(query);
}
function extend(o,p){
for(prop in p){
o[prop] = p[prop];
}
return o;
}
function calctime(time){
var hours,minutes,seconds,timer='';
hours = String(parseInt(time / 3600));
minutes = String(parseInt((time % 3600)/60));
seconds = String(parseInt((time % 60)));
if(hours !== '0'){
if(hours.length === 1) hours ='0'+hours;
timer+=(hours+':');
}
if(minutes.length === 1 ){
minutes ='0'+minutes;
}
timer+=(minutes+":");
if(seconds.length === 1){
seconds = '0'+seconds;
}
timer+=seconds;
return timer;
}
if(win.XMLHttpRequest === undefined){
win.XMLHttpRequest = function(){
try{
return new ActiveXObject('Msxml2.XMLHTTP.6.0');
}catch(e1){
try{
return new ActiveXObject('Msxml2.XMLHTTP.3.0');
}catch(e2){
throw new Error('XMLHttpRequset is not supported!');
}
}
};
}
function ajax(url,type,isasync,callback){
if(!url) return false;
if(!type) type = 'GET';
if(!isasync) isasync = false;
if(!callback) callback = function(result){
console.log(result);
}
var xhr = new XMLHttpRequest();
xhr.open(type,url,isasync);
xhr.onreadystatechange = function(){
if(xhr.readyState === 4 && xhr.status=== 200){
var type = xhr.getResponseHeader('Content-Type');
if(type.indexOf('xml') !== -1 && xhr.responseXML) callback(xhr.responseXML);
else if(type === 'application/json')
callback(JSON.parse(xhr.responseText));
else
callback(xhr.responseText);
}
};
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
xhr.send(null);
}
})(window);