javascript - setAttribute 不覆盖另一个类属性
问题描述
我创建了一个代码,当您在我的网站正文的选择中选择一个选项时,会在类中包含一个带有 setAttribute 的新属性,但我的问题是它删除了暗模式的另一个属性。
代码的目的是更改网站的某些颜色,并将其保存到本地存储中。
我能改变什么?
function wow(value) {
var index = {
chb: "griegos",
cj: "romanos",
hv: "celtas"
};
document.getElementById("body").setAttribute("class", index[value]);}
.griegos {background: orange}
.romanos {background: purple}
.celtas {background: green}
<body id="body" class="griegos dark">
<select class="forminput" onchange="wow(this.value)"><option value="chb">Camp Half-Blood</option><option value="cj">Camp Jupiter</option><option value="hv">Hotel Valhalla</option></select></div>
解决方案
一种选择如下;使用Element.classList
API:
// ensuring that we look for elements after the document
// is loaded and elements are present, by waiting for
// the 'DOMContentLoaded' event to fire:
window.addEventListener('DOMContentLoaded', () => {
// named function, which receives the 'evt'
// (a reference to the Event Object) passed
// automatically from the (later) use of
// EventTarget.addEventListener():
function wow(evt) {
var index = {
chb: "griegos",
cj: "romanos",
hv: "celtas"
};
// here we look for the relevant element via its
// id:
document.getElementById("body")
// we use Element.classList.remove() to remove
// previously-chosen class-names:
.classList.remove(
// we use an Array-literal with the spread
// syntax to create an Array of the options
// within the <select>:
[...evt.target.options]
// Array.prototype.map() lets us to return
// a new Array based on the former Array:
.map(
// and here we pass the relevant class-name
// returned from the index Object based on
// the current option's value:
(opt) => index[opt.value]
)
);
// once those class-names are removed, we once again
// select the relevant element based on its id, and
// use Element.classList.add() to add the relevant
// class-name, again from the index Object:
document.getElementById("body").classList.add(
index[evt.currentTarget.value]
);
}
// here use document.querySelector() to find the <select>
// element using a CSS selector:
document.querySelector('select.forminput')
// and bind the event-handling using
// EventTarget.addEventListener(), to bind the wow()
// function to handle the 'change' event:
.addEventListener('change', wow);
});
.griegos {
background: orange
}
.romanos {
background: purple
}
.celtas {
background: green
}
<body id="body" class="griegos dark">
<select class="forminput">
<option value="chb">Camp Half-Blood</option>
<option value="cj">Camp Jupiter</option>
<option value="hv">Hotel Valhalla</option>
</select>
</body>
推荐阅读
- javascript - 为什么 puppeteer 评估函数返回空对象
- shell - 如何比较shell脚本中的浮点值?
- unity3d - 在 Unity 中为播放器设置动画时动画控制器中的多个项目
- python - 带有一些不熟悉的错误的循环导入错误
- r - 用另一个向量的条件替换一个向量的多个值
- python - 创建说命令 discord.py
- javascript - 当您的 HTML 中使用 Javascript 进行分页时,是否可以创建导出为 CSV 按钮?
- reactjs - 调用可为空的函数时,打字稿不会引发错误
- java - 如何使用 Jackson 序列化具有重复键的数据结构?
- javascript - EJS ERROR: SyntaxError: missing ) 在编译 ejs 时参数列表后