You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Roblox星码选择器网页中用Local Storage保存背景色

修复LocalStorage保存背景色功能并解决网站崩溃问题

之前你尝试用Cookie或LocalStorage保存背景色时网站崩溃,大概率是因为没正确处理存储的初始值,或是类型转换出错导致数组索引异常。以下是修复后的完整代码,同时实现背景色的持久化保存:

<!DOCTYPE html>
<html>
<head>
    <title>Starcode Selector</title>
    <style>
        body {
            background-color: #999999; /* Default background color */
        }
        #Starcodeselector {
            margin-left: 850px;
        }
        #Generate {
            margin-left: 925px;
        }
        #code {
            margin-left: 820px
        }
    </style>
</head>
<body>
    <button id="settingsbutton" onclick="changeBackgroundColor()">
        <img src="https://th.bing.com/th/id/OIP.bYjHRWzPofO43ZMBzzdVngHaHM?pid=ImgDet&rs=1" alt="settings" width="75" height="75">
    </button>
    <h1 id="Starcodeselector">Starcodeselector</h1>
    <button onclick="generateCode()" id="Generate">Generate</button>
    <div id="code"></div>

    <script>
        const starcodes = ["DV", "NOODLES", "OLIX", "LCLC", "LAUGH", "SCRIPTED", "REALKREEK"];
        const colors = ["blue","green","red","pink","purple","black","yellow","#999999"];

        // 从LocalStorage读取保存的颜色索引,不存在则用默认值0
        let selectedColor = parseInt(localStorage.getItem('selectedColor')) || 0;
        // 页面加载时恢复背景色
        document.body.style.backgroundColor = colors[selectedColor];

        function changeBackgroundColor() {
            selectedColor = (selectedColor + 1) % colors.length;
            document.body.style.backgroundColor = colors[selectedColor];
            // 将新的颜色索引保存到LocalStorage
            localStorage.setItem('selectedColor', selectedColor);
        }

        function generateCode() {
            const number = Math.floor(Math.random() * starcodes.length);
            const code = "Use Starcode " + starcodes[number] + " when buying robux!";
            document.getElementById('code').innerText = code;
            console.log("color=" + selectedColor)
        }
    </script>
</body>
</html>

关键修改说明:

  • 初始化读取LocalStorage:脚本开头通过localStorage.getItem('selectedColor')获取保存的索引,用parseInt转换为数字(因为LocalStorage存储的是字符串),如果没有保存过则默认使用0。
  • 页面加载恢复背景色:读取到索引后立即设置body的背景色,确保打开页面时直接应用之前的设置。
  • 切换颜色后保存:在changeBackgroundColor函数中,更新索引后立即调用localStorage.setItem保存最新值,确保每次切换都持久化。

这样修改后,背景色设置会被保存到浏览器的LocalStorage中,下次访问网页时会自动恢复,同时不会出现按钮失效的崩溃问题。

内容的提问来源于stack exchange,提问作者Kssonety

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 14:57:40