復制代碼 代碼如下:
window.onload = function(){
var gaga = document.getElementById( "gaga" );
addClass( gaga,"gaga1" )
addClass( gaga,"gaxx" );
removeClass( gaga,"gaga1" )
removeClass( gaga,"gaga" )
function hasClass( elements,cName ){
return !!elements.className.match( new RegExp( "(\\s|^)" + cName + "(\\s|$)") ); // ( \\s|^ ) 判斷前面是否有空格 (\\s | $ )判斷後面是否有空格 兩個感歎號為轉換為布爾值 以方便做判斷
};
function addClass( elements,cName ){
if( !hasClass( elements,cName ) ){
elements.className += " " + cName;
};
};
function removeClass( elements,cName ){
if( hasClass( elements,cName ) ){
elements.className = elements.className.replace( new RegExp( "(\\s|^)" + cName + "(\\s|$)" )," " ); // replace方法是替換
};
};
};