我正在创建一个基于网页的游戏,它有6种不同的背景颜色,在整个过程中交替。当按钮在页面上被按下时,它会在下一页上设置一个新的颜色。但是,如果页面刷新,它会恢复到原来的颜色。我知道我需要在会话中存储颜色,这样就不会发生这种情况,但不幸的是,我正在努力做到这一点,因为我是JavaScript的新手,到目前为止我所尝试的一切都不起作用。
这是我目前拥有的JavaScript:
<script>
function backgroundYellow() {
document.body.style.backgroundColor = "#F7B538";
}
</script>
<script>
function backgroundBlue() {
document.body.style.backgroundColor = "#3CB9C4";
}
</script>
<script>
function backgroundPink() {
document.body.style.backgroundColor = "#C33C55";
}
</script>
<script>
function backgroundGreen() {
document.body.style.backgroundColor = "#8CB369";
}
</script>
<script>
function backgroundOrange() {
document.body.style.backgroundColor = "#E57A44";
}
</script>
<script>
function backgroundPurple() {
document.body.style.backgroundColor = "#606CA8";
}
</script>
如果你只瞄准HTML5浏览器,那么我建议你使用本地存储。您可以在浏览器本身中存储名称-值对。下面是一个很好的开始方式:http://www.w3schools.com/html/html5_webstorage.asp
的例子:
// Store
localStorage.setItem("lastname", "Smith");
// Retrieve
document.getElementById("result").innerHTML = localStorage.getItem("lastname");
如果你想沿着使用会话的路线走下去,那么你应该考虑在你的游戏中添加服务器端功能-如果你是初学者,PHP可能是最好的。
使用本地存储,像这样的东西应该可以工作
html<body onload="revertColor()">
js
function revertColor(){
if(typeof(Storage) !== "undefined") {
// Code for localStorage/sessionStorage
if (localStorage.getItem("backgroundColor") === null)
document.body.style.backgroundColor=localStorage.getItem("backgroundColor");
else//background is not set-local storage enabled/exists
backgroundYellow();//or default color
} else {
// Sorry! No Web Storage support..
backgoundYellow();//or default color function
}
}
//for your color functions
funtion backgoundYellow(){
document.body.style.backgroundColor = "#606CA8";
localStorage.setItem("backgroundColor", "#606CA8");
}