CSS 样式切换方法详细讲解

样式与数据分离所带来的不只是符合标准这样的简单,样式既然与数据分离那么样式的切换则变得理所当然的了!但是网上这样的中文教程实在是太少了!所以我收集了一部分中外网站已经实现的技术资料整理出来供网友参考。

首先要具备不同内容的CSS文件(最好每个文件代表一种样式,或是代表需要作出变动的部分)。这里以三个为例:

第一个是背景为红色的CSS文件(red.css)CSS中的内容为:

body {background-color:red;}

第二个是背景为绿色的CSS文件(green.css)CSS中的内容为:

body {background-color:green;}

第三个是背景为黄色的CSS文件(yellow.css)CSS中的内容为:

body {background-color:yellow;}

然后在xthml文件中加入这三个CSS的链接

<link rel=”alternate stylesheet” href=”red.css” mce_href=”red.css” type=”text/css” title=”red” media=”screen, projection”/>

<link rel=”stylesheet” href=”green.css” mce_href=”green.css” type=”text/css” title=”green” media=”screen, projection”/>

<link rel=”alternate stylesheet” href=”yellow.css” mce_href=”yellow.css” type=”text/css” title=”yellow” media=”screen, projection”/>

这三个中除了title不一样外还有一个地方有所不同,那就是REL。第一个与第三个都是alternate stylesheet只有第二个是stylesheet。这第二个就是当然样式。

在链接下面再导入一个JS文件,用来控制这个样式切换

function setActiveStyleSheet(title) {

var i, a, main;

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) return a.getAttribute(‘title’);

}

return null;

}

在合适的地方加入三个切换按钮

第 1 2 3 页

CSS 样式切换方法详细讲解

相关文章:

你感兴趣的文章:

标签云: