用javascript來實現頁面的換膚功能

來源:互聯網
上載者:User

js實現換膚功能的實現主要是通過利用js控制CSS來實現的。大致的實現原理是這樣的,

1、先定義一個頁面基本樣式style.css來確定div的寬高等屬性,使得整個頁面的DIV元素有一個基本的架構結構。

2、再定義一系列的樣式color1.css,color2.css……用來確定DIV元素的背景顏色,邊框顏色等等。

3、用JS函數來決定調用哪個樣式,並把調進來的樣式寫進cookie,這樣就可以達功能。

例如:我們的頁面結構如下:

 1<div id="header"></div>
 2<div id="contant"></div>
 3<div id="footer"></div>
 4-------------------------------------------
 5style.css
 6#header{width:700px;height:120px; margin:0px auto;}
 7#contant{width:700px;height:400px; margin:0px auto;}
 8#footer{width:700px;height:200px; margin:0px auto;}
 9-------------------------------------------
10color1.css
11#header,#contant,#footer{boder:1px solid #dfaf33; background-color:#eeeeee;}
12-------------------------------------------
13color2.css
14#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函數:

 1function getObject(elementId) { //擷取指定id的object
 2 if (document.getElementById) {
 3  return document.getElementById(elementId);
 4 } else if (document.all) {
 5  return document.all[elementId];
 6 } else if (document.layers) {
 7  return document.layers[elementId];
 8 }
 9}
10function changeStyle(id){//轉場樣式
11 var stylesheet=getObject("color").href="css/color"+id+".css";
12 document.cookie="stylesheet="+escape(stylesheet);//寫入Cookie
13 //alert(document.cookie);
14 //alert(stylesheet);
15}
16
17
18function initStyle(){ //初始化樣式,如果cookie存在樣式,則載入cookie樣式,否則載入預設樣式
19  if(/stylesheet=([^;]+)/.test(document.cookie))//判斷是否存在cookie.
20   getObject("color").href=unescape(RegExp.$1);
21   //alert(/stylesheet=([^;]+)/.test(document.cookie));
22}
23initStyle();
24

出自:http://www.cnblogs.com/38809972/articles/952115.html

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.