首页/网站建设外包/用javascript+css来实现网站页面的换肤功能

用javascript+css来实现网站页面的换肤功能

发布-xiaoming | 浏览量-

JS实现换肤功能的实现主要是通过利用JS控制CSS来实现的。

大致的实现原理是这样的:
1、先定义一个页面基本样式style.css来确定div的宽高等属性,使得整个页面的DIV元素有一个基本的框架结构。
2、再定义一系列的样式color1.css,color2.css……用来确定DIV元素的背景颜色,边框颜色等等。
3、用JS函数来决定调用哪个样式,并把调进来的样式写进cookie,这样就可以达功能。

例如:我们的页面结构如下:
<div id="header"></div>
<div id="contant"></div>
<div id="footer"></div>
-------------------------------------------
style.css
#header{width:700px;height:120px; margin:0px auto;}
#contant{width:700px;height:400px; margin:0px auto;}
#footer{width:700px;height:200px; margin:0px auto;}
-------------------------------------------
color1.css
#header,#contant,#footer{boder:1px solid #dfaf33; background-color:#eeeeee;}
-------------------------------------------
color2.css
#header,#contant,#footer{boder:1px solid #ff00ea; background-color:#ff3322;}
-------------------------------------------
页面中这两行比较关键:
<link href="css/style.css" rel="stylesheet" type="text/css" />
<link href="css/color1.css" id="color" rel="stylesheet" type="text/css" />
第1行引入页面的基本样式,第2行引入一个颜色样式color2.css给页面一个初始化颜色,第2行中有一个id="color"这个很关键它为JS函数提供了

接口,js通过这个id改变href的值来决定引入那个颜色样式,从而达到改变页面颜色样式的目的。
改变颜色样式的按钮我们可以用文字链接来实现,也可以用其他元素来实现。
<a onclick="changeStyle(1)">样式1</a>
<a onclick="changeStyle(2)">样式2</a>
--------------------------------------------
实现这些功能的js函数:
function getObject(elementId) { //获取指定id的object
if (document.getElementById) {
   return document.getElementById(elementId);
} else if (document.all) {
   return document.all[elementId];
} else if (document.layers) {
   return document.layers[elementId];
}
}
function changeStyle(id){//切换样式
var stylesheet=getObject("color").href="css/color"+id+".css";
document.cookie="stylesheet="+escape(stylesheet);//写入Cookie
//alert(document.cookie);
//alert(stylesheet);
}


function initStyle(){ //初始化样式,如果cookie存在样式,则加载cookie样式,否则加载默认样式
   if(/stylesheet=([^;]+)/.test(document.cookie))//判断是否存在cookie.
    getObject("color").href=unescape(RegExp.$1);
    //alert(/stylesheet=([^;]+)/.test(document.cookie));
}
initStyle();

原文地址:http://www.35ui.cn/post/20100508996.html

标签jQuery教程静态网页模板制作网络推广外包北京服务器租用css网页培训班网站优化培训

上一条: DreamWeaver网页设计教程经典50问
下一条: JS如何获取屏幕浏览器网页高度宽度

或许你还对下面的文章感兴趣