2015-05-25 103 views
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> 

回答

1

這是你正在尋找的代碼:

<script type="text/javascript"> 
    var body = document.body; 

    window.addEventListener('load', function() { 
     var currentStyle = localStorage.getItem('currentStyle'), 
      newStyle=1; 
     if (currentStyle !== null) { 
      newStyle = currentStyle % 3 + 1; 
     } 

     body.classList.add('bg-' + newStyle); 
     localStorage.setItem('currentStyle', newStyle); 
    }); 

    window.addEventListener('storage', function (event) { 
     var currentStyle = localStorage.getItem('currentStyle'); 
     body.classList.remove('bg-' + event.oldValue); 
     body.classList.add('bg-' + currentStyle); 
    }); 
</script> 
+0

是的!兄弟,非常感謝你! – Aleksandr