用户可以从下拉列表中选择一个主题,所选主题将存储在本地存储中。虽然它可以将下拉值保存在本地存储中,但它不会调用样式表。请帮忙,谢谢!
请原谅弗兰肯斯坦式的代码。 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/