我嘗試用 JavaScript 測驗自己,所以我決定用 JavaScript 在codepen中制作可變主題網站這是我的代碼:在此處輸入影像描述
但它沒有用。請幫幫我。
uj5u.com熱心網友回復:
雖然@LoaiMasri可以很好地解決問題,但仍有很大的改進方法。如果您有更多主題要添加,特別是使代碼更短,更高效。
對于LoaiMasri的解決方案,您應該考慮的第一個更改是使用switch- 陳述句而不是列出大量 -if/else陳述句。
但是,對于少數幾個主題而言,這將變得復雜。最有效的方法是通過 CSS 添加主題。為此,您執行LoaiMasrivalue在選項標簽上使用 -attribute 的方法。但是,給它一個更直接的值,例如theme-1,theme-2...
然后你使用下面的腳本:
document.getElementById('Themes').addEventListener('change', function() {
document.body.className = "";
let theme = document.getElementById("Themes").value;
document.body.classList.add(theme);
});
document.body.className = "";-> 這將從body-tag 中洗掉所有類并用作重置。
let theme = document.getElementById("Themes").value;->value從option-tag 中獲取。
document.body.classList.add(theme);-> 現在這將向 -tag 添加一個類,該類body等于-tagvalue的option。
您現在所要做的就是向您的 CSS 添加與 -tag 相同的value類option。現在,無論您要添加多少主題(已經比LoaiMasri的解決方案更小),這將用 5 行 JS 代碼解決問題。
document.getElementById('Themes').addEventListener('change', function() {
document.body.className = "";
let theme = document.getElementById("Themes").value;
document.body.classList.add(theme);
});
.theme-1 {
background-color: white;
color: black;
}
.theme-2 {
background-color: black;
color: white;
}
.theme-3 {
background-color: darkgray;
color: white;
}
<select id="Themes">
<option value="theme-1">White</option>
<option value="theme-2">Black</option>
<option value="theme-3">Dark</option>
</select>
uj5u.com熱心網友回復:
document.getElementById("Themes").addEventListener("change", function () {
document.body.style.backgroundColor = this.value;
});
這是一個答案,但我建議將值添加為數字
喜歡這段代碼
<select id="Themes">
<option value="1">White</option>
<option value="2">Black</option>
<option value="3">Dark</option>
</select>
document.getElementById("Themes").addEventListener("change", function () {
let theme = document.getElementById("Themes").value;
if (theme == 1) {
document.body.style.backgroundColor = "white";
document.body.style.color = "black";
} else if (theme == 2) {
document.body.style.backgroundColor = "black";
document.body.style.color = "white";
} else if (theme == 3) {
document.body.style.backgroundColor = "darkgrey";
document.body.style.color = "white";
}
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/481772.html
標籤:javascript html dom 主题
