如何通过单击按钮将css href更改为所有.html文档?

时间:2013-11-07 19:54:37

标签: javascript jquery html css href

我有这个HTML代码:

<link id="style1" rel="stylesheet" href="css/style.css" type="text/css" media="screen">

用这个js:

<script type='text/javascript'>
function toggle() {
    var el = document.getElementById("style1");
    if (el.href.match("css/style.css")) {
        el.href = "css/style-b.css";    
    }
    else {
        el.href = "css/style.css";  
    }
}

<button type="button" onclick="toggle()">Switch</button>

所以,我需要做:当我点击这个按钮来改变Css Href和我的其他.html文件..所以让我们说..当我从index.html转到带链接的contact.html时,我需要改变css。

怎么做? (如果没有办法用HTML / JS做这个,我有其他选择吗?)

感谢

2 个答案:

答案 0 :(得分:1)

两个可能的想法: 1.使用cookie保存状态,并在调用每个页面时检查(http://www.w3schools.com/js/js_cookies.asp) 2.使用本地存储来保存状态。一般来说,它就像一个cookie,它更容易访问。 (http://diveintohtml5.info/storage.html

所以在你的脚本中你需要添加

localStorage.setItem("style", "-b");

然后你需要在代码中的其他地方

localStorage.getItem("style"), 

并检查是否存在

var el = document.getElementById("style1");
var style = localStorage.getItem("style");
if(style !== null && style == "b"){
  el.href = "css/style-b.css";
} else {
  el.href = "css/style.css";
}  

function toggle() {
 var el = document.getElementById("style1");
 if (el.href.match("css/style.css")) {
   el.href = "css/style-b.css"; 
   localStorage.setItem("style", "b");   
 }
 else {
   el.href = "css/style.css";
   localStorage.setItem("style", "a");  
 }
}

答案 1 :(得分:0)

两种方式,使用带有Javascript的GET或POST变量,将使用服务器端会话变量传递到每个页面或正确的方式。