当前位置: 首页 > 图文教程 > 网络编程 > Javascript > setAttribute方法实现网页两种样式表

Javascript
form中限制文本字节数js代码
use jscript with List Proxy Server Information
use jscript List Installed Software
List Installed Software Features
List Information About the Binary Files Used by an Application
List the Codec Files on a Computer
List the UTC Time on a Computer
List Installed Hot Fixes
excel操作之Add Data to a Spreadsheet Cell
Add Formatted Data to a Spreadsheet
Apply an AutoFormat to an Excel Spreadsheet
JavaScript语法着色引擎(demo及打包文件下载)
类之Prototype.js学习
一款JavaScript压缩工具:X2JSCompactor
iis6+javascript Add an Extension File
jscript之Open an Excel Spreadsheet
jscript之Read an Excel Spreadsheet
jscript之List Excel Color Values
去除图像或链接黑眼圈的两种方法总结
Add a Formatted Table to a Word Document

Javascript 中的 setAttribute方法实现网页两种样式表


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-10-13   浏览: 336 ::
收藏到网摘: n/a

今天研究了一下JS的用setAttribute方法实现一个页面两份样式表的效果,具体方法如下:

第一步:在连接样式表的元素里定义一个id,例如

<link href="1.css" rel="stylesheet" type="text/css" id="css">

我定义的id是css。

第二步:写一个js函数,代码如下:

<script type="text/javascript">
function change(a){
 var css=document.getElementById("css");
  if (a==1)
  css.setAttribute("href","1.css");
  if (a==2)
  css.setAttribute("href","2.css");
}
</script>

这个函数的code可以放在页面的任何地方。

第三步:为改变页面的样式表的连接添加一个函数的触发事件,代码如下:

<a href="#" onClick="change(1)">1.css</a>
<a href="#" onClick="change(2)">2.css</a>

该效果在IE和FF下均测试通过,相信大家看完后因该非常明了,利用这个方法我们可以让浏览者自己选择需要显示的样式表,比如年老者可以选择一个字体较大的样式表。这里需要注意的两点是:

  1. 在这个例子中函数名function后面的名字不能为links或者link,如果为links或者link,样式表将不被改变,具体什么原因我也不大清楚,可能是javascript的保留字符。
  2. 另外如果是改变整个页面的样式,你需要在样式表文件里定义body的高度为100%