我正在尝试使用此代码更改我的头部和按钮颜色
<div class="ann-right">
<button id="red" onclick="color1('#D91E18'), color2('#96281B')" class="tooltip color" title="Red"></button>
<button id="green" onclick="color1('#3FC380'), color2('#00B16A')" class="tooltip color"title="Green" ></button>
<button id="blue" onclick="color1('#5BBBFF'), color2('#22A7F0')" class="tooltip color" title="Blue"></button>
</div>
<script>
function color1(col){
document.getElementById("head").style.backgroundColor=col;
}
function color2(col){
document.getElementById("submit-search").style.backgroundColor=col;
document.getElementById("submit-post").style.backgroundColor=col;
}
</script>
如何在页面刷新后保持颜色?
答案 0 :(得分:1)
有多种方法可以实现所需的行为,其中一种方法是使用sessionStorage。将所选颜色保存在sessionStorgae中,并在页面加载时读取它。有关详细信息,请参阅以下内容:
// Save data to sessionStorage
sessionStorage.setItem('key', 'value');
// Get saved data from sessionStorage
var data = sessionStorage.getItem('key');
// Remove saved data from sessionStorage
sessionStorage.removeItem('key');
// Remove all saved data from sessionStorage
sessionStorage.clear();
更新:对于您的情况:
<div class="ann-right">
<button id="red" onclick="color1('#D91E18'), color2('#96281B')" class="tooltip color" title="Red"></button>
<button id="green" onclick="color1('#3FC380'), color2('#00B16A')" class="tooltip color" title="Green"></button>
<button id="blue" onclick="color1('#5BBBFF'), color2('#22A7F0')" class="tooltip color" title="Blue"></button>
</div>
<script>
function color1(col) {
document.getElementById("head").style.backgroundColor = col;
sessionStorage.setItem('col1', col);
}
function color2(col) {
document.getElementById("submit-search").style.backgroundColor = col;
document.getElementById("submit-post").style.backgroundColor = col;
sessionStorage.setItem('col2', col);
}
color1(sessionStorage.getItem('col1'));
color2(sessionStorage.getItem('col2'));
</script>