首页 > 解决方案 > 使用 Alpine JS Persist Plugin 在刷新/重新访问页面后记住活动的切换/选项卡

问题描述

我按照教程使用 Alpine js 在我的网站上放置了一个暗模式切换器。它工作得很好,但是每次用户刷新页面时,他们都需要再次选择暗模式选项。我在网上搜索,发现 Persist Plugin 似乎是一个解决方案,但是,我没有任何专业背景,并且只有在网上按照教程构建我的网站的经验,所以我无法真正让它工作。谁能帮我这个?太感谢了 :)

下面是我使用的教程代码,它来自 Oxygen Builder 教程:

<script src="//unpkg.com/alpinejs" defer></script>

<style>
    .darkmode-switcher {
        width: 64px;
        height: 32px;
        border-radius: 80px;
        display: flex;
        flex-direction: row;
        align-items: center;
        justify-content: flex-start;
        padding: 2px;
        cursor: pointer;
        background-color: #191919;
        transition: 0.3s all ease-in-out;
    }
    
    .darkmode-switcher__circle {
        width: 28px;
        height: 28px;
        border-radius: 80px;
        background-color: white;
        transition: 0.3s all ease-in-out;
    }   
</style>

<div class="mode-switcher" x-data="{ darkMode: false, switchMode: function() { this.darkMode = !this.darkMode } }">
    <div class="darkmode-switcher" @click="switchMode()">
        <div class="darkmode-switcher__circle"></div>
    </div>
    <template x-if="darkMode">
        <style>
            .darkmode-switcher {
                background-color: white;
            }
            .darkmode-switcher__circle {
                background-color: black;
                transform: translateX(32px);
            }
            
            .content-wrapper {
                background-color: black;
            }
            
            .content {
                color: white;
                background-color: #191919;
            }
            body {
                background-color: black;
            }
        </style>
    </template>
</div>

标签: javascriptalpine.js

解决方案


推荐阅读