gpt4 book ai didi

javascript - LocalStorage单击添加/删除类

转载 作者:行者123 更新时间:2023-12-01 02:20:50 25 4
gpt4 key购买 nike

我有一个工作脚本,它添加背景颜色并将其保存在本地存储中。我想将其转换为 addClass。我不知道任何JS。将 .css 更改为 .addClass 时遇到的问题是它不会删除以前选择的背景颜色。获取 body class="c-wit c-rood c-ori"

不知何故,它在 Stackoverflow 上不起作用。但也许有人知道我如何删除主体类并添加新的主体类。

if (localStorage.getItem("background") != null) {
getColour = localStorage.background;
$('body').css('background', getColour);
}

$(".c-ori").click(function () {
setColour = '#0c1534';
localStorage.removeItem('background');
$('body').css('background', setColour);
localStorage.setItem("background", setColour);
});
$(".c-wit").click(function () {
setColour = '#fff';
localStorage.removeItem('background');
$('body').css('background', setColour);
localStorage.setItem("background", setColour);
});
$(".c-rood").click(function () {
setColour = '#B71C1C';
localStorage.removeItem('background');
$('body').css('background', setColour);
localStorage.setItem("background", setColour);
});
*{box-sizing:border-box;}

html{color:#fff; height:100%;}
body{background:#0c1534; margin:0; padding:0; height:100%; transition:0.5s;}

.kleur{text-align:center; position:fixed; top:10px; left:15px; z-index:1; height:30px; color:#fff; font-size:8px; font-family:arial;}
.kleur div{width:18px; height:18px; line-height:16px; border:1px solid #fff; margin:5px 2px; display:inline-block; cursor:pointer; border-radius:100%; }

.c-ori{background:#0c1534;}
.c-wit{background:#ffffff; color:#000;}
.c-rood{background:#B71C1C;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="kleur">
<div class="c-ori">1</div>
<div class="c-wit">2</div>
<div class="c-rood">3</div>
</div>

最佳答案

也许是这样的?它将覆盖 body 元素的类名

if (localStorage.getItem("background") != null) {
getColour = localStorage.background;
document.body.className = getColour;
}

$(".c-ori").click(function () {
setColour = "c-ori"
document.body.className = setColour
localStorage.setItem("background", setColour);
});

关于javascript - LocalStorage单击添加/删除类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49236289/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com