JavaScript访问控制外部CSS并判断浏览器版本

来源:互联网 发布:西安网络招聘信息 编辑:程序博客网 时间:2024/05/17 03:33

其实很多或者说大部分CSS文件对网页的描述都是以外部CSS的身份出现的,所以当需要做一些需要JS改变CSS而

出现的动态效果的时候,JS不得不去访问外部CSS,下面我们就来探讨一下JS访问外部CSS的例子。

这个例子就是点击按钮触发事件来改变DIV的背景颜色。首先请看CSS文件

.style1{width: 400px;height: 500px;background-color: red;}

然后是HTML文件

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <title>test.html</title>    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">    <meta http-equiv="description" content="this is my page">    <meta http-equiv="content-type" content="text/html; charset=UTF-8">        <script type="text/javascript">function test(eventObj){//获取mycss.css中的所有类选择器//这个0的意思是HTML页面中引入的第一个cssvar cssResult = document.styleSheets[0].rules;//获取指定的CSS类选择器,根据下标var style1 = cssResult[0];if(eventObj.value=="黑色"){style1.style.backgroundColor="black";}else{style1.style.backgroundColor="red";}}function test1(){if(window.XMLHttpRequest){if(!window.ActiveXObject){alert("Mozilla, Safari");}elsealert("IE");}else{alert("IE6");}}    </script>  <link rel="stylesheet" href="../css/6.css" type="text/css"></link>  </head>    <body> <div id="div1" class="style1">div1</div> <input type="button" value="黑色" onclick="test(this);"/>   <input type="button" value="红色" onclick="test(this);"/>   <br/><br/><br/>   <input type="button" value="检测浏览器版本" onclick="test1();"/>  </body></html>

function test(eventObj){//获取mycss.css中的所有类选择器//这个0的意思是HTML页面中引入的第一个cssvar cssResult = document.styleSheets[0].rules;//获取指定的CSS类选择器,根据下标var style1 = cssResult[0];if(eventObj.value=="黑色"){style1.style.backgroundColor="black";}else{style1.style.backgroundColor="red";}}
这个函数就是,其中的含义都已经介绍,应该说是一种很好的访问外部CSS的方式,当然了,对于浏览器的兼容需要

判断浏览器的版本,test1()函数说明了这个,分别是使用ActiveX的window的空间支持与否来判断,其实应该有更加全面的,回来再 研究。


原创粉丝点击