我正在尝试使用HTML和JavaScript制作基本主题切换代码。但如果我回击或刷新,选择将被取消,页面恢复正常。
我可以在JavaScript中添加任何功能,以便选择保持到缓存清理或类似的东西吗?
var x = 0;
var themeValue = 0;
function changeTheme3() {
themeValue ++;
if (themeValue > 2) {
themeValue = 1;
}
if (themeValue == 1) {
document.body.style.backgroundColor = "grey";
} else if (themeValue == 2) {
document.body.style.backgroundColor = "white";
}
}
button {
display: block;
margin: 0 auto;
padding: 0;
width: 250px;
height: 70px;
border: 2px solid #1ECD97;
border-radius: 40px;
background: transparent;
color: #1ECD97;
letter-spacing: 1px;
font-size: 18px;
font-family: 'Montserrat', sans-serif;
}
button:hover {
background-color: #1ECD97;
color: #fff;
}
<div id="theme-button">
<button type="button" onclick="changeTheme3()">Change Theme</button>
</div>
答案 0 :(得分:0)
我建议使用LocalStorage。如果您希望用户能够自定义他们的体验,您需要将其保存在某个地方。这通常通过会话或数据库完成,但这两者都是后端解决方案。
对于前端,您可以选择设置Cookie或使用localstorage。如果您希望主题选择仅限于一个会话,您还可以使用sessionStorage
实施
function changeTheme3() {
themeValue ++;
if (themeValue > 2) {
themeValue = 1;
localStorage.setItem('themeValue', themeValue);
}
if (themeValue == 1) {
document.body.style.backgroundColor = "grey";
} else if (themeValue == 2) {
document.body.style.backgroundColor = "white";
}
}
然后,在加载页面的某个地方,您需要从存储中提取此值。 (注意,localStorage将值保存为字符串,因此您在检索时可能需要parseInt()
值。
function loadTheme(){
if (localStorage && localStorage.getItem('themeValue'){
var storedTheme = parseInt(localStorage.getItem('themeValue'));
//do your logic to set the theme based on value
} else {
//do nothing or choose to set your default theme as the value into storage
}
}
一方面注意,根据您支持的浏览器,您可能需要确保检查是否支持localStorage。它对任何现代浏览器都有很好的支持。
答案 1 :(得分:-1)
你可以使用sqlite html5来做到这一点,例如检查这个链接http://www.html5rocks.com/en/tutorials/webdatabase/todo/:D
这里是简单的例子先生
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript">
var db = openDatabase('db', '1.0', 'theme selector', 1000); //db name, version, desc, size in byte
var msg;
db.transaction(function (tx) {
tx.executeSql('CREATE TABLE IF NOT EXISTS THEME (id unique, theme)');
});
db.transaction(function (tx) {
tx.executeSql('SELECT * FROM THEME WHERE id = 1', [], function (tx, results) {
var len = results.rows.length, i;
var value = 'theme_1';
if(len == 0 ){
tx.executeSql('INSERT INTO THEME (id, theme) VALUES (1, ?)', [value]);
}else{
value = results.rows.item(0).theme;
}
document.querySelector('#theme_selected').innerHTML = value;
document.getElementById('theme_select').value = value;
}, null);
});
function update (){
var selector = document.getElementById('theme_select');
var value = selector[selector.selectedIndex].value;
db.transaction(function (tx) {
tx.executeSql('UPDATE THEME SET theme = ? WHERE id=1', [value]);
document.querySelector('#theme_selected').innerHTML = value;
});
}
</script>
</head>
<body>
<select id="theme_select">
<option value="theme_1" >theme 1</option>
<option value="theme_2">theme 2</option>
</select>
<button onclick="update()">update</button>
<div id="theme_selected"></div>
</body>
</html>