[英]Swap style sheet with localstorage
I'm a designer and JS is completely foreign to me. 我是设计师,JS对我来说完全陌生。 I'd like to keep localstorage of the selected stylesheet after refresh.
刷新后,我想保留所选样式表的本地存储。 I was able to find code to swap stylesheet, but I'm not sure what code to add to use localstorage
我能够找到用于交换样式表的代码,但是不确定使用localstorage添加哪些代码
<!DOCTYPE html>
<html>
<head>
<link id="pagestyle" rel="stylesheet" type="text/css" href="style1.css">
<script>
function swapStyleSheet(sheet){
document.getElementById('pagestyle').setAttribute('href', sheet);
}
</script>
</head>
<body>
<h2>Javascript Change StyleSheet Without Page Reload</h2>
<button onclick="swapStyleSheet('style1.css')">Dark Style Sheet</button>
<button onclick="swapStyleSheet('style2.css')">Blue Style Sheet</button>
<button onclick="swapStyleSheet('style3.css')">Default Style Sheet</button>
</body>
</html>
you can use this code 您可以使用此代码
<script>
var swapStyleSheet = function (sheet) {
document.getElementById('pagestyle').setAttribute('href', sheet);
storebackground(sheet);
}
var storebackground = function (swapstylesheet) {
localStorage.setItem("sheetKey", swapstylesheet); //you need to give a key and value
}
var loadbackground = function () {
document.getElementById('pagestyle').setAttribute('href', localStorage.getItem('sheetKey'));
}
window.onload = loadbackground();
</script>
Use addEventListener
instead, you will probably need to add some other stuff in window.onload
event. 使用
addEventListener
代替,您可能需要在window.onload
事件中添加其他内容。 An minimal working example with it: 一个最小的工作示例:
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" id="style">
<script type="text/javascript">
window.addEventListener('load', function() {
let style = document.getElementById('style');
let select = document.getElementById('select');
let value = localStorage.getItem('style');
if (value !== null) {
style.setAttribute('href', value);
select.value = value;
}
select.addEventListener('change', function() {
style.setAttribute('href', select.value);
localStorage.setItem('style', select.value);
});
});
</script>
</head>
<body>
<select id="select">
<option value="style1.css">Style 1</option>
<option value="style2.css">Style 2</option>
<option value="style3.css">Style 3</option>
</select>
</body>
</html>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.