HTML
<a href="javascript:;" class="mdui-btn mdui-btn-icon" mdui-tooltip="{content: '切换模式'}" onclick="switchNightMode()"><i class="mdui-icon material-icons">wb_sunny</i></a>
JS
<script>
        function setCookie(cname, cvalue, exdays) {
            var d = new Date();
            d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
            var expires = "expires=" + d.toGMTString();
            document.cookie = cname + "=" + cvalue + "; " + expires;
        }
        function getCookie(cname) {
            var name = cname + "=";
            var ca = document.cookie.split(';');
            for (var i = 0; i < ca.length; i++) {
                var c = ca[i].trim();
                if (c.indexOf(name) == 0) return c.substring(name.length, c.length);
            }
            return "";
        }
        function switchNightMode() {
            var mode = getCookie("mode");
            if (mode == 'light' | mode == '') {
                document.body.classList.add('mdui-theme-layout-dark');
                setCookie("mode", "night", 30);
                // document.cookie = "mode=night";
                console.log('夜间模式开启');
            } else {
                document.body.classList.remove('mdui-theme-layout-dark');
                setCookie("mode", "light", 30);
                // document.cookie = "mode=light"
                console.log('夜间模式关闭');
            }
        }
    </script>
上面的代码实现的功能是 当我点击按钮,切换模式,比如说从正常模式切换到夜间模式.
现在问题出现了,当我点击这个按钮,可以切换到夜间模式, 却无法从夜间模式切换到正常模式.
控制台始终输出的结果是"夜间模式开启".
我开始还以为是我的 JS 代码里面设置 cookie 和获取 cookie 这部分代码写错了,后来又检查了很多遍,没有发现问题出现在哪里,麻烦各位大佬指点一下
|  |      1avk458      2020-06-03 15:53:30 +08:00  1 | 换成 || 。。。。。。。 | 
|  |      2wb500      2020-06-03 15:56:51 +08:00 。。。。。 | 
|  |      3StanLx      2020-06-03 16:00:09 +08:00 。。。。。。 | 
|      4dbldong      2020-06-03 16:01:07 +08:00 。。。。。。。 | 
|      6ahsjs      2020-06-03 16:45:35 +08:00  1 没通过域名访问吧,你这个加上这个 ```js Object.defineProperty(document,'cookie',{writable: true}); ``` | 
|      7icecrack      2020-06-03 17:04:26 +08:00  1 你这个是通过浏览器直接打开网页的方式导致的问题(使用 file 协议时,因为一些安全原因,有些 js 功能是不生效啊的),搭建一个本地 WEB 服务器再运行就没有问题了。使用 vscode 添加 live server 插件可以方便的搭建本地 WEB 服务器。 | 
|  |      8maichael      2020-06-03 17:18:45 +08:00  1 #6#7 是正解,file 协议 cookie 不可写。 |