javascript - 带有本地存储的下拉 CSS

标签 javascript css drop-down-menu local-storage

用户可以从下拉列表中选择一个主题,所选主题将存储在本地存储中。虽然它可以将下拉值保存在本地存储中,但它不会调用样式表。请帮忙,谢谢!

请原谅弗兰肯斯坦式的代码。 JS 对我来说很陌生,我的职业是设计师。

<html>
<head>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
    <link href="style1.css" rel="stylesheet" type="text/css" title="s1" id="s1"/>
</head>
<body>

<select id="mySelect" class="test">
    <option value="style1.css">Option A</option>
    <option value="style2.css">Option B</option>
    <option value="style3.css">Option C</option>
</select>


<!--local storage-->
<script>
 $('.test').change(function() {
    localStorage.setItem(this.id, this.value);
}).val(function() {
    return localStorage.getItem(this.id)
});
</script>
<!--dropdown css-->

 <script>
        function setStyleSource (linkID, sourceLoc) {
      var theLink = document.getElementById(linkID);
      theLink.href = sourceLoc;
      console.log(theLink.href);
    }

    document.getElementById("mySelect").addEventListener("change", function(){
        var selected = this.options[this.selectedIndex].value;
        setStyleSource ("s1", selected)
    });
    </script>


</body>
</html>

1.更改CSS的下拉菜单有效。 2.所选选项的本地存储有效。 但是 存储的选定选项实际上并不显示其自己的 css 表(而是显示默认的 css)。

最佳答案

val() 改变 dropdownvalue 不会触发 change 事件,你必须在设置值后手动触发它:

$('.test').val(localStorage.getItem(this.id)).trigger('change'); // OR .change()

同时为 change 添加事件监听器 before 触发相同的:

function setStyleSource(linkID, sourceLoc) {
  var theLink = document.getElementById(linkID);
  theLink.href = sourceLoc;
  console.log(theLink.href);
}

document.getElementById("mySelect").addEventListener("change", function() {
  var selected = this.options[this.selectedIndex].value;
  setStyleSource("s1", selected)
});

$('.test').change(function() {
  localStorage.setItem(this.id, this.value);
}).val(function() {
  return localStorage.getItem(this.id)
}).trigger('change');

关于javascript - 带有本地存储的下拉 CSS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47726565/

相关文章:

javascript - Bootstrap : How might I keep a dropdown menu open to click within a nested dropdown?

javascript - 为什么我的 Bootstrap 的下拉菜单不起作用?

html - 多下拉子菜单未正确显示

javascript - 使用 1.5K、1M、1G 等公制前缀格式化 javascript 数字

javascript - JS如何调用函数并从另一个文件传递参数

javascript - 为什么我必须在 ES6 的映射闭包中使用 return ?

jquery - 为什么下拉菜单在 IE9 中不起作用?

html - Internet Explorer Div 宽度问题

html - 如何使表单位于所有其他 css 之上?

javascript - 寻找最接近的可能坐标