Javascript 如何通过单击按钮将css href更改为所有.html文档?
我有以下HTML代码:Javascript 如何通过单击按钮将css href更改为所有.html文档?,javascript,jquery,html,css,href,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/
<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>
函数切换(){
var el=document.getElementById(“样式1”);
if(el.href.match(“css/style.css”)){
el.href=“css/style-b.css”;
}
否则{
el.href=“css/style.css”;
}
}
转换
所以,我需要做:当我点击这个按钮来更改Css Href和我的其他.html文档。。那么让我们说。。当我使用link从index.html转到contact.html时,我也需要更改css
如何做到这一点?(如果用HTML/JS无法做到这一点,我还有其他选择吗?)
谢谢两个可能的想法:
1.使用cookie保存状态,并在调用每个页面()时检查
2.使用本地存储来保存状态。一般来说,它就像一块饼干,更容易访问。()
因此,在脚本中,您需要添加
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");
}
}
有两种方法,一种是在Javascript中使用GET或POST变量,这将传递到每个页面;另一种是在服务器端会话变量中使用正确的方法。我是初学者,因此可能需要更多帮助。请添加一个示例。希望能有帮助。