答案 0 :(得分:0)
您的脚本将在每次加载页面时运行。您需要存储选定的值,并在页面加载时进行检查。
function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
function changeColor(el) {
var theme = el.value;
document.body.style.background = theme;
createCookie('siteTheme', theme, 365);
}
$(function() {
var theme = readCookie('siteTheme');
if( theme != '' && theme != 'undefined') {
document.body.style.background = theme;
}
});
&#13;
<select onchange="javascript:changeColor(this);">
<option selected disabled hidden>Theme</option>
<optgroup label="Themes">
<option value="white">Light</option>
<option value="#222222">Dark</option>
<option value="red">Red</option>
</optgroup>
</select>
&#13;
答案 1 :(得分:0)
您可以将所需的颜色存储在localStorage
:
游乐场:http://jsbin.com/cisicay/2/edit?html,css,js,console,output
// On page load let's see if we stored any theme color
var theme = window.localStorage.theme;
// This function can be both triggered as Standalone
// or on Select onchange event:
function changeColor(el) {
// If it was triggered by our Select element store the new theme color
if(el) theme = window.localStorage.theme = el.value;
// Set the color
if(theme) document.body.style.background = theme;
}
// Trigger theme change on page load
changeColor();
<select onchange="changeColor(this);">
<option disabled hidden>Theme</option>
<optgroup label="Themes">
<option value="#eee">Light</option>
<option value="#222">Dark</option>
<option value="red">Red</option>
</optgroup>
</select>
此处的另一个示例将更改您的select
值以及页面加载和回退到#eee
( light 变体)
( note :为此,请删除默认的selected
选项属性!并为SELECT元素添加ID)
游乐场:http://jsbin.com/cisicay/3/edit?html,js,console,output
function changeColor(el) {
document.body.style.background = localStorage.theme = el ? el.value : localStorage.theme || "#eee";
document.getElementById("theme").value = localStorage.theme
}
changeColor();
<select id="theme" onchange="changeColor(this);">
<option disabled hidden>Theme</option>
<optgroup label="Themes">
<option value="#eee">Light</option>
<option value="#222">Dark</option>
<option value="red">Red</option>
</optgroup>
</select>