我是设计师,JS对我来说完全陌生。刷新后,我想保留所选样式表的本地存储。我能够找到交换样式表的代码,但是不确定使用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>
最佳答案
您可以使用此代码
<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>