【发布时间】:2019-08-20 23:32:54
【问题描述】:
我有一个按钮,每次单击它时都会随机生成背景颜色。我想让它成为localstorage 函数,这样每次我关闭或重新加载页面时,我最后点击的背景颜色都会保留在网页上。
var link = document.getElementById("bglink");
var output = document.getElementById("output");
link.addEventListener("click", getRandom);
function getRandom(){
var newColor = '#'+Math.floor(Math.random()*16777215).toString(16);
var rgbColor = newColor.replace('#','');
var r = parseInt(rgbColor.substring(0,2), 16);
var g = parseInt(rgbColor.substring(2,4), 16);
var b = parseInt(rgbColor.substring(4,6), 16);
var result = 'rgba(' + r + ',' + g + ',' + b + ')';
document.body.style.backgroundColor = newColor;
output.textContent = newColor + " - " + result;
}
$("#bglink").click(function () {
var bgcolor = document.body.style.backgroundColor;
localStorage.setItem("bgcolor", document.body.style.backgroundColor);
alert('Background colour ' + bgcolor + ' saved in localStorage');
});
重新加载时,页面应设置为单击按钮时设置的最后一种颜色。
【问题讨论】:
-
您查看 localStorage.getItem 了吗?您可以检查颜色是否存在,如果存在,则可以应用它。这应该是您逻辑的第一步。其余的看起来不错。
标签: javascript jquery rest express npm