Cookie

作者: 啃香菜的花萝萝 | 来源:发表于2019-07-02 21:08 被阅读0次

1. Cookie 概念

  • cookie 是由服务器端生成,发送给 User-Agent。浏览器会将cookie以key/value的形式保存到某个目录下的文本文件中。下次请求同一网站时就发送该cookie给服务器。
  • 每个浏览器都有一个cookie文件
  • cookie大小有限制,大约都在4k左右。

2. 基本用法

在Console中使用document.cookie可以获取当前的所有cookie

效果
同时也可以添加cookie,也是通过这个document.cookie,例子如下:
<body>
    <script>
        var oDate = new Date();
        oDate.setDate(oDate.getDate() + 3);
        // console.log(oDate);
        document.cookie = 'age=18; max-age=1000';
        document.cookie = 'name=sun; expires=' + oDate;
        document.cookie = 'test=session';
    </script>
</body>
代码效果
注意,设置了过期时间的cookie会到过了时间才被注销,而 Session这条cookie在浏览器关闭后,就会不见了的。

3. 封装函数增删改查cookie

其中 removeCookie 的操作就是调用 setCookie函数,将其过期时间设成 -1 即可。
由于document.cookie 返回的结果是一个字符串,所以查找某个cookie的value,即函数getCookie 需要有拆分字符串成数组这样的操作。

<body>
    <script>
        document.cookie = 'age=18; max-age=1000';
        document.cookie = 'test=session'; 

        var manageCookie = {
            setCookie: function(name, value, time) {
                document.cookie = name + '=' + value + ';max-age=' + time;
                return this;
            },
            removeCookie: function (name) {
                return this.setCookie(name, '', -1);
            },
            getCookie: function(name, cb) {
                var allCookieArr = document.cookie.split('; ');
                console.log(allCookieArr);
                for (var i = 0; i < allCookieArr.length; i++) {
                    var itemCookieArr = allCookieArr[i].split('=');
                    console.log(itemCookieArr);
                    if (itemCookieArr[0] === name) {
                        cb(itemCookieArr[1]);
                        return this;
                    }
                }
                cb(undefined);
                return this;
            }
        }

        manageCookie
            .setCookie('color', 'pink', 3000)
            .setCookie('id', '7', 5000)
            .removeCookie('age')
            .getCookie('id', function (data) {
                console.log(data);
            })
    </script>
</body>
代码结果
代码结果

4. Demo

做一个小方块拖拽,cookie存储小方块位置,页面关闭后再次打开时,小方块能处于上次关闭时候的位置。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Cookie Demo</title>
    <style>
        #square {
            position: absolute;
            top: 100px;
            left: 100px;
            width: 100px;
            height: 100px;
            background-color: pink;
        }
    </style>
</head>
<body>
    <div id="square"></div>
    <script>
        var oSquare = document.getElementById('square');

        var manageCookie = {
            setCookie: function(name, value, time) {
                document.cookie = name + '=' + value + ';max-age=' + time;
                return this;
            },
            removeCookie: function (name) {
                return this.setCookie(name, '', -1);
            },
            getCookie: function(name, cb) {
                var allCookieArr = document.cookie.split('; ');
                // console.log(allCookieArr);
                for (var i = 0; i < allCookieArr.length; i++) {
                    var itemCookieArr = allCookieArr[i].split('=');
                    // console.log(itemCookieArr);
                    if (itemCookieArr[0] === name) {
                        cb(itemCookieArr[1]);
                        return this;
                    }
                }
                cb(undefined);
                return this;
            }
        }
        // 拖拽功能
        var drag = {
            init: function(dom) {
                this.dom = dom;
                var _this = this;
                this.bindEvent();
                manageCookie.getCookie('newLeft', function (data) {
                    if (data) {
                        _this.dom.style.left = data + 'px';
                    }
                }).getCookie('newTop', function (data) {
                    if (data) {
                        _this.dom.style.top = data + 'px';
                    }
                })
            },
            bindEvent: function () {
                this.dom.onmousedown = this.mouseDown.bind(this);
            },
            mouseDown: function (e) {
                document.onmousemove = this.mouseMove.bind(this);
                document.onmouseup = this.mouseUp.bind(this);

                this.disX = e.clientX - this.dom.offsetLeft;
                this.disY = e.clientY - this.dom.offsetTop;
            },
            mouseMove: function(e) {
                this.newLeft = e.clientX - this.disX;
                this.newTop = e.clientY - this.disY;
                this.dom.style.left = this.newLeft + 'px';
                this.dom.style.top = this.newTop + 'px';
            },
            mouseUp: function () {
                document.onmousemove = null;
                document.onmouseup = null;
                manageCookie.setCookie('newLeft', this.newLeft, 10000).setCookie('newTop', this.newTop, 10000);
            }
        };

        drag.init(oSquare);
    </script>
</body>
</html>
代码效果

相关文章

网友评论

      本文标题:Cookie

      本文链接:https://www.haomeiwen.com/subject/rtuycctx.html