在项目中我们总会遇到,可以切换主题的项目,比如这样:

当用户选择主题切换,选定某一主题之后, 切换到相应主题的样式文件,而且在刷新页面的时候,样式依旧生效,而不是仅次于当前页面,那怎么实现这种功能呢?
我们可以把用户点击之后的样式文件通过生命一个变量 将其存到本地,当页面刷新进入新页面之后,调用刚刚切换的样式文件,就可以实现这种效果(缺陷就是:会有短暂的留白,望 大神指教)
附上代码:
link css样式文件正常引入即可
html(部分)
<li class="dropdown">
<a class="dropdown-toggle" data-toggle="dropdown">
<span style="font-size: 18px" class="colour">主题切换</span>
<b class="caret"></b>
</a>
<ul class="dropdown-menu">
<li>
<a th:onclick="'javascript:themeOne('+${1}+')'">护眼黄</a>
<a th:onclick="'javascript:themeOne('+${2}+')'">天空蓝</a>
<a th:onclick="'javascript:themeOne('+${3}+')'">素雅白</a>
</li>
</ul>
</li>
js
<script>
var stylePath
var styleCss
// var headLink
function themeOne(n) {
switch(n)
{
case 1:
let obj = document.getElementById('modifyCss')
// obj.setAttribute('href' , '/libs/theme/pblog/css/common01.css')
styleCss = '/libs/theme/pblog/css/common01.css'
obj.setAttribute('href' , styleCss)
localStorage.setItem("stylePaths",styleCss)
console.log(localStorage.getItem('stylePaths'))
// stylePath = localStorage.getItem('stylePaths')
break
case 2:
let obj1 = document.getElementById('modifyCss')
// obj1.setAttribute('href' , '/libs/theme/pblog/css/common02.css')
styleCss = '/libs/theme/pblog/css/common02.css'
obj1.setAttribute('href' , styleCss)
localStorage.setItem("stylePaths",styleCss)
console.log(localStorage.getItem('stylePaths'))
// stylePath = localStorage.getItem('stylePaths')
break
case 3:
let obj2 = document.getElementById('modifyCss')
// obj2.setAttribute('href' , '/libs/theme/pblog/css/web-common.css')
styleCss = '/libs/theme/pblog/css/web-common.css'
obj2.setAttribute('href' , styleCss)
localStorage.setItem("stylePaths",styleCss)
console.log(localStorage.getItem('stylePaths'))
// stylePath = localStorage.getItem('stylePaths')
break
default:
alert('没有该选项')
}
}
function re() {
var headLink = document.createElement("link")
headLink.setAttribute("rel" , "stylesheet")
headLink.setAttribute("id" , "modifyCss")
headLink.setAttribute("href" , stylePath)
var bodyPage = document.getElementById("pageId")
bodyPage.appendChild(headLink)
};
re()
function fun() {
stylePath = localStorage.getItem('stylePaths')
if(stylePath == null) {
stylePath = '/libs/theme/pblog/css/web-common.css'
}
let pageCss = document.getElementById('modifyCss')
pageCss.setAttribute('href' , stylePath)
console.log(stylePath)
}
fun()
</script>
当然 这块函数 你可以写成 自调用函数,
如有问题 :欢迎私信 指正!
本文介绍了一种通过JavaScript和localStorage实现网页主题切换的方法。用户选择的主题将被保存,并在页面刷新时保持不变。文章提供了实现这一功能的具体代码示例。
1224

被折叠的 条评论
为什么被折叠?



