【发布时间】:2018-08-21 23:32:32
【问题描述】:
我试图在页面刷新时保持样式表设置的当前主题。
我目前正在用页面底部的一排按钮换出 css 文件。
如何添加以下代码,以便在使用 cookie 刷新页面时设置和检查当前样式表?
所以当用户刷新页面时,当前选择的主题将保持原位,直到选择另一个主题?
jQuery
$("#css-light").click(function() {
$("link[rel=stylesheet]").attr({href : "stylesheet.css"});
});
$("#css-dark").click(function() {
$("link[rel=stylesheet]").attr({href : "stylesheetdark.css"});
});
<button onclick="location.href='#dark'" id="css-dark" class="" type="button">Dark</button>
<button onclick="location.href='#light'" id="css-light" class="" type="button">Light</button>
谢谢
最小、完整和可验证的示例,包含所提供解决方案的代码。
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<link rel="stylesheet" href="css/stylesheet.css" type="text/css">
<meta charset="UTF-8">
<title>Switch CSS Themes and Store as a Cookie</title>
</head>
<body>
<script>
//suggested code answer
var sheet = document.querySelector("link[rel=stylesheet]"); // id might be better on `<link>`
var theme = localStorage.getItem('theme');
if (theme && theme !== sheet.getAttribute('href')) {
sheet.setAttribute('href', theme);
}
// Theme selection script
$(document).ready(function() {
// light
$("#css-light").click(function() {
$("link[rel=stylesheet]").attr({
href: "css/stylesheet.css"
});
localStorage.setItem('theme', "stylesheet.css")
});
// dark
$("#css-dark").click(function() {
$("link[rel=stylesheet]").attr({
href: "css/stylesheetdark.css"
});
localStorage.setItem('theme', "stylesheetdark.css")
});
</script>
Site Content
</body>
<footer>
Theme
<button onclick="location.href='#dark'" id="css-dark" class="button-footer" type="button">Light</button>
<button onclick="location.href='#light'" id="css-light" class="button-footer" type="button">Dark</button>
</footer>
</html>
【问题讨论】:
标签: jquery css cookies themes jquery-cookie