0
如何確保當您在同一選項卡中更改背景色時,背景顏色會在另一個選項卡中更改?現在,頁面重新加載時背景顏色會發生變化。我想在挖掘兩個相同的選項卡時做到這一點,並更新其中一個會改變背景和其他。更改頁面背景。 LocalStorage
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Untitled</title>
<style>
html, body {
height: 100%;
}
body {
margin: 0;
padding: 0;
display: flex;
align-items: center;
justify-content: center;
}
.bg-1 {
background: chocolate;
}
.bg-2 {
background: aqua;
}
.bg-3 {
background: grey;
}
h1 {
color: white;
font-size: 3em;
}
</style>
</head>
<body>
<h1>Change the background color of the page when you reload.</h1>
<script>
var body = document.body,
currentStyle = +localStorage.currentStyle || 0;
window.addEventListener('load', function() {
body.classList.add('bg-' + (currentStyle + 1));
localStorage.currentStyle = ++currentStyle % 3;
});
window.addEventListener('storage', function(event) {
body.classList.remove('bg-' + event.oldValue);
body.classList.add('bg-' + (currentStyle + 1));
console.log(event.key);
});
</script>
</body>
</html>
是的!兄弟,非常感謝你! – Aleksandr