更改页面背景。 localStorage的

时间:2015-05-25 10:34:02

标签: javascript

如何确保在同一选项卡中更改背景颜色时,背景颜色会在另一个中更改?现在,重新加载页面时背景颜色会发生变化。我想在挖掘两个相同的标签时这样做,更新其中一个会改变背景和另一个。

<!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 个答案:

答案 0 :(得分: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>