我試圖在重繪 瀏覽器時保持不同元素的背景顏色相同這是一個筆記網站專案,一個人可以添加任意數量的筆記,所以我想保存他們選擇的顏色,每個顏色都可以不同元素(注釋),然后重繪 瀏覽器時顏色將保持不變。
這是“元素如何顯示”的代碼
function showNote2() {
console.log("Show");
let note = localStorage.getItem("notes");
if(note == null){
noteData = []
// message.innerText = "Please Add a Note"
}
else{
noteData = JSON.parse(note);
};
let showBox = "";
noteData.forEach(function show(element, index) {
showBox = `<div id="cardID" style="width: 18rem;">
<select id="mySelect${index}" style="text-align:center" onchange="changeColor(${index})">
<option id="bckgrnd-clr" value="white">Background Color</option>
<option value="Red">Red</option>
<option value="Green">Green</option>
<option value="Blue">Blue</option>
</select>
<div id="card${index}">
<h5 >Note
${index 1}
</h5>
<p >
${element}
</p>
<button id="${index}" onclick="deleteNote(this.id)" >Delete Note</a>
</div>
</div>
})
let showNote3 = document.getElementById("notes2");
if(noteData.length != 0){
showNote3.innerHTML = showBox;
}else{
showNote3.innerHTML = "Please add a Note"
}
}`
這是用于應用顏色的函式:
function changeColor(index,e) {
console.log("Change",e)
let note = localStorage.getItem("notes");
if(note != null ){
let showNote3 = document.getElementById(`card4${index}`)
console.log(showNote3)
let colorApply = document.getElementById(`card${index}`)
console.log(colorApply)
let elm1 = document.getElementById(`mySelect${index}`)
console.log(elm1)
let color = elm1.options[elm1.selectedIndex].value;
colorApply.style.backgroundColor = color;
localStorage.setItem(`clr${index}`, color)
}
else{
`Note is Empty`
}
這是我用來存盤和呼叫所選值的代碼。在存盤值時它作業得很好,但在回傳時它不起作用。
function backGroundClr(index) {
let backclr2 = localStorage.getItem(`clr${index}`)
colorApply.style.backgroundColor = backclr2
console.log(backGroundClr)
}
謝謝
uj5u.com熱心網友回復:
在您的回圈中,在生成模板之前加載您的顏色。然后在模板中使用
noteData.forEach(function show(element, index) {
color = localStorage.getItem(`clr${index}`) || 'white'
showBox = `
<div id="card${index}" style="background-color:${color}">
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/405947.html
標籤:
上一篇:我需要幫助將自定義javascript添加到除一個之外的所有網站頁面
下一篇:不是函式,什么時候函式就在上面?
