使用localstorage交换样式表

时间:2017-12-10 08:06:35

标签: javascript css local-storage

我是设计师,JS对我来说完全陌生。我想在刷新后保留所选样式表的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>

2 个答案:

答案 0 :(得分:0)

您可以使用此代码

<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>

答案 1 :(得分:0)

改为使用addEventListener,您可能需要在window.onload事件中添加其他内容。一个最小的工作示例:

<!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>