我正在创建一个页面,用户可以通过下拉菜单更改页面上的多个外观/样式,这会更改css文件名。我已设法通过下拉菜单更改样式表,但我现在想将当前的css文件保存在本地存储上。例如,如果用户更改为stylesheet3.css(通过下拉菜单),则下次用户访问页面时将设置此样式/外观。这是我的代码:
HTML:
function changeStyleFunction() {
var href;
var value = document.getElementById("changeStyle").value;
localStorage.setItem("GetData" , value); //Here is my biggest problem???
href = value;
document.getElementById('myStyleSheet').href = href;
}
JavaScript的:
`r result <- TabelaTipos("T")`
`r result[1]`
如何让当前样式表(值)进入localStore?我是Local Storages的新手......谢谢!
答案 0 :(得分:4)
首先,您应确保已加载文档,然后读取localstorage中的值:
main.js:
(function () {
var DEFAULT_CSS = 'stylesheet.css',
styleElement,
styleOption;
document.addEventListener('DOMContentLoaded', function (e) {
var styleElement = document.getElementById('myStyleSheet'),
styleOption = document.getElementById("changeStyle"),
currentCSS = localStorage.getItem('GetData') || DEFAULT_CSS;
styleElement.href = currentCSS;
styleOption.value = currentCSS;
styleOption.addEventListener('change', changeStyleFunction);
});
function changeStyleFunction() {
var newCSS = styleOption.value;
localStorage.setItem('GetData', newCSS);
styleElement.href = newCSS;
}
}());
的index.html:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<link id="myStyleSheet" href="stylesheet.css" rel="stylesheet" type="text/css">
</head>
<body>
<div id="changeLook">
Change style: <select id="changeStyle">
<option value="stylesheet.css">Default Style</option>
<option value="stylesheet1.css">Style 1</option>
<option value="stylesheet2.css">Style 2</option>
<option value="stylesheet3.css">Style 3</option>
</select>
</div>
<script src="main.js" type="text/javascript"></script>
</body>
</html>
stylesheet.css中:
#changeLook {
background-color: #eee;
}
stylesheet1.css:
#changeLook {
background-color: #ff0000;
}
stylesheet2.css:
#changeLook {
background-color: #00ff00;
}
stylesheet3.css:
#changeLook {
background-color: #0000ff;
}
编辑:我添加了所有文件。
EDIT2:是的,这是我忘记在文档就绪时分配变量的错误,抱歉,现在应该没问题。
答案 1 :(得分:1)
试试这个:
<script>
document.addEventListener("DOMContentLoaded", function()
{
var defaultCSS="defaultCSS.css";
var yourHref=localStorage.getItem("GetData");
if(typeof yourHref === 'undefined' || yourHref === null)
{
document.getElementById('myStyleSheet').href=defaultCSS;
}
else
{
document.getElementById('myStyleSheet').href=yourHref;
}
});
</script>