利用JavaScript来切换样式表

时间:2022-05-25 23:18:46

切换样式表

  1. html页
     <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
    
     <html xmlns="http://www.w3.org/1999/xhtml"> 
    
     <head> 
    
     <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
    
     <title>样式表切换</title> 
    
     <link href="css/default.css" type="text/css" rel="stylesheet" rev="stylesheet" title="default" /> 
    
     <link href="css/alternate.css" type="text/css" rel="alternate stylesheet" rev="alternate" title="alternate" /> 
    
     <script src="javascript/样式切换.js" type="text/javascript" language="javascript"> 
    
     </script> 
    
     </head> 
    
     <body> 
    
     <!—设置样式表表为默认样式表 --> 
    
     <input type="button" value="style1" onclick="setActiveStyleSheet('default');" /> 
    
     <!--设置样式表表为可选样式表 --> 
    
     <input type="button" value="style2" onclick="setActiveStyleSheet('alternate');" /> 
    
     <!—获取当前样式表的对应 title --> 
    
     <input type="button" value="get stylesheet" onclick="getActiveStyleSheet('alternate');" /> 
    
     </body> 
    
     </html> 

    Html代码

  2. default.css
     body 
    
     { 
    
         background-color:green; 
    
     } 

alternate.css

 body
{
background-color:blue;
}
样式切换.js
 // JavaScript Document 

 function setActiveStyleSheet(title) { 

 var i, a; 

 if (title) 

  { 

     for(i=0; (a = document.getElementsByTagName('link')[i]); i++) 

     { 

         if(a.getAttribute('rel').indexOf('style') != -1 && a.getAttribute('title')) 

          { 

             a.disabled = true; 

             if(a.getAttribute('title') == title) 

             a.disabled = false; 

         } 

     } 

  } 

 } 

 function getActiveStyleSheet() { 

 var i, a; 

 for(i=0; (a = document.getElementsByTagName('link')[i]); i++) { 

 if(a.getAttribute('rel').indexOf('style') != -1 && a.getAttribute('title') && !a.disabled) alert(a.getAttribute('title')); 

 } 

 }