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.classListAPI:

// 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>

JS Fiddle demo

  • 箭头功能。
  • Array.prototype.map().
  • document.getElementById().
  • document.querySelector().
  • EventTarget.addEventListener().
  • 扩展语法(...).

最新更新