我在我的博客上设置了一个选项,可以通过单击按钮来更改某些div的样式(
以光明、黑暗和污浊为主题
)。为了做得更好,我需要在访问者选择一个时,将该样式保存在本地存储中,但我不知道如何做到这一点。
我在网上看了很多例子,但没有一个符合我的情况,我迷路了。
这是我的代码:
具有onclick函数的botton
:
<button onClick="lightTheme()" class="button light">Light</button>
<button onClick="grayTheme()" class="button default">Default</button>
<button onClick="darkTheme()" class="button dark">Dark</button>
我的完整JAVASCRIPT:
function lightTheme(){
var ele = document.getElementsByClassName('picArea');
for (var i = 0; i < ele.length; i++ ) {
ele[i].style.backgroundColor = "#EEE";
ele[i].style.borderColor = "#000";
}
var ele = document.getElementsByClassName('picTitle');
for (var i = 0; i < ele.length; i++ ) {
ele[i].style.color = "#111";
}
var ele = document.getElementsByClassName('picNumber');
for (var i = 0; i < ele.length; i++ ) {
ele[i].style.backgroundColor = "#AAA";
ele[i].style.color = "#111";
}
}
function darkTheme(){
var ele = document.getElementsByClassName('picArea');
for (var i = 0; i < ele.length; i++ ) {
ele[i].style.backgroundColor = "#222";
ele[i].style.borderColor = "#000";
}
var ele = document.getElementsByClassName('picTitle');
for (var i = 0; i < ele.length; i++ ) {
ele[i].style.color = "#fff";
}
var ele = document.getElementsByClassName('picNumber');
for (var i = 0; i < ele.length; i++ ) {
ele[i].style.backgroundColor = "#";
ele[i].style.color = "#EEE";
}
}
function grayTheme(){
var ele = document.getElementsByClassName('picArea');
for (var i = 0; i < ele.length; i++ ) {
ele[i].style.backgroundColor = "#777";
ele[i].style.borderColor = "#000";
}
var ele = document.getElementsByClassName('picTitle');
for (var i = 0; i < ele.length; i++ ) {
ele[i].style.color = "#fff";
}
var ele = document.getElementsByClassName('picNumber');
for (var i = 0; i < ele.length; i++ ) {
ele[i].style.backgroundColor = "#555";
}
}
。。。如果有帮助:
HTML上的我的div:
<div class="picArea"><p class="picTitle">Picture X<span class="picNumber">1</span></p></div>
<div class="picArea"><p class="picTitle">Picture X<span class="picNumber">2</span></p></div>
<div class="picArea"><p class="picTitle">Picture X<span class="picNumber">3</span></p></div>
CSS(仅用于演示):
.picArea {
border: 1px solid #000;
background: #777;
padding: 5px;
margin: 5px 0;
}
.picTitle {
font-size: 150%;
margin: 0;
color: #fff;
}
.picNumber {
padding: 0 7px;
background: #555;
border-radius: 50%;
margin-left: 10px;
color: #ccc;
font-size: 80%;
}
.button {
width: 75px;
height: 50px;
border-radius: 50%;
border: none;
}
.button.light {
background: #ccc;
color: #000;
}
.button.dark {
background: #000;
color: #fff;
}
.button.default {
background: #777;
color: #fff;
}
预览:
https://i.stack.imgur.com/ncneS.jpg