换肤,带有本地储存功能

<!DOCTYPE HTML >
< html >
< head >
     < meta charset= "utf-8" >
     < title >CSS主题切换 </ title >
     <!-- <link rel="stylesheet" type="text/css" href="css/a.css" title="a" ty="theme"> -->
</ head >

< body >
     < div class= "main" >
         < div class= "con" >
             < ul >
                 < li onclick= "setStyleSheet(this)" value= "" >换肤 </ li >
                 < li onclick= "setStyleSheet(this)" value= "css/a.css" >主题a </ li >
                 < li onclick= "setStyleSheet(this)" value= "css/b.css" >主题b </ li >
             </ ul >
         </ div >
     </ div >
     < script type= "text/javascript" >
         /**
        * 替换css样式文件;
        * @param title:替换的css样式文件名称及路径
        * auth:JYX time:2016.07.28
        */
         function setStyleSheet( title){
             // 找到head
             var doc_head = document. head;
             // 找到所有的link标签
             var link_list = document. getElementsByTagName( "link");
             if ( link_list ){
                 for ( var i= 0;i< link_list. length;i++ ){
                     if ( link_list[i]. getAttribute( "ty") === "theme" ){
                         // 找到后将这个link标签重head中移除
                         doc_head. removeChild(link_list[i]);
                    }
                }
            }
             // 创建一个新link标签
             var link_style = document. createElement( "link");
             // 对link标签中的属性赋值
             link_style. setAttribute( "rel", "stylesheet");
             link_style. setAttribute( "type", "text/css");
             link_style. setAttribute( "href", title. getAttribute( "value"));
             link_style. setAttribute( "ty", "theme");
             // 加载到head中最后的位置
             doc_head. appendChild(link_style);
             // 本地存储
             var color_value= title. getAttribute( "value");
             window. localStorage. setItem( "color_value",color_value)
        };
         var color_value = window. localStorage. getItem( "color_value");
         if(color_value){
             // 创建一个新link标签
             var link_style = document. createElement( "link");
             var doc_head = document. head;
             // 对link标签中的属性赋值
             link_style. setAttribute( "rel", "stylesheet");
             link_style. setAttribute( "type", "text/css");
             link_style. setAttribute( "href",color_value);
             link_style. setAttribute( "ty", "theme");
             // 加载到head中最后的位置
             doc_head. appendChild(link_style);
        }

     < / script >
</ body >
</ html >

猜你喜欢

转载自blog.csdn.net/qq_36371276/article/details/80621109