【问题标题】:Swap style sheet with localstorage与本地存储交换样式表
【发布时间】:2018-05-24 00:51:33
【问题描述】:

我是一名设计师,JS 对我来说完全陌生。我想在刷新后保留所选样式表的本地存储。我能够找到代码来交换样式表,但我不确定要添加什么代码来使用本地存储

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

【问题讨论】:

标签: javascript css local-storage


【解决方案1】:

您可以使用此代码

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-04-18
      • 2020-01-24
      • 2017-09-22
      • 2011-03-14
      • 2011-03-01
      • 2012-01-04
      相关资源
      最近更新 更多