使用Java脚本更改背景颜色并在刷新页面后保留 [英] Changing Background colour with Javascript and keeping it after refreshing the page
本文介绍了使用Java脚本更改背景颜色并在刷新页面后保留的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
使用Java单击按钮时,我正在更改背景的颜色.
I'm changing the colour of the background when a button is clicked with Javascript.
这是JS代码:
<script>
function myFunction() {
document.body.style.backgroundColor = "#BB0A21";
}
</script>
它可以正常工作,但是问题在于,当用户刷新页面时,背景色被重置为原始颜色.有办法阻止这种情况发生吗?
It works fine, but the problem is that when the user refreshes the page, the background colour is being reset to the original colour. Is there a way to stop this from happening?
谢谢, 丽莎
推荐答案
您可以将颜色更改存储在本地会话中.您需要检查会话是否已经具有该值,如果没有,请进行设置.这将在页面刷新等情况下继续存在
you can store the colour change in a local session. You'll need to check if the session already has the value, setting it if not. this will survive page refreshes etc
function myFunction() {
if (sessionStorage.getItem('colour')) {
document.body.style.backgroundColor = sessionStorage.getItem('colour');
}else{
document.body.style.backgroundColor = "#BB0A21";
sessionStorage.setItem('colour', "#BB0A21");
}
}
// then you'll need to call your function on page load
myFunction();
这篇关于使用Java脚本更改背景颜色并在刷新页面后保留的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文