【前端开发】本地化存储

1.cookie

  • 为什么有cookie?

    • http 是上下文无关,无状态协议

    • set-cookie 服务器设置

    • cookie可以存储在浏览器中,每次发送网络请求的时候会携带cookie

  • cookie的特点

    • cookie不可跨域

    • cookie存储在浏览器里面

    • cookie有数量与大小的限制

      • 数量在50个左右

      • 大小在4kb左右

    • cookie的存储时间非常灵活

    • cookie不光可以服务器设置,客户端也可以设置

  • cookie的属性

    • name  cookie的名字,唯一性

    • value cookie的值

    • domain 设置cookie在哪个域下是有效的

    • path  cookie的路径

    • expires cookie的过期时间

      • GMT

    • max-age cookie的有效期

      • -1,0,正数

    • HttpOnly 有这个标记的cookie,前端是无法获取的(后端设置)

    • Secure 设置cookie只能有过https协议传输(后端设置)

    • SameSite 设置cookie在跨域请求的时候不能被发送(后端设置)

2.封装cookie操作及拖拽应用

let manageCookie = {
   set(name, value, data) {
     document.cookie = name + '=' + value + '; ' + 'max-age=' + data
   },
   get(name) {
     let cookieItems = document.cookie.split('; ')
     for (let item = 0; item < cookieItems.length; item++) {
       let itemCookie = cookieItems[item].split('=')
       if (itemCookie[0] == name) {
         return itemCookie[1]
       }
     }
   },
   remove(name) {
     this.set(name, '', 0)
   }
 }
 let moveDome = {
   init(dom){
     this.dom = dom;
     this.bindEvent()
​
     let l = manageCookie.get('left');
     let t= manageCookie.get('top');
     this.dom.style.left = l ? l + 'px':0;
     this.dom.style.top = t ? t + 'px' : 0
   },
   bindEvent(){
     this.dom.onmousedown = this.onmouseDown.bind(this)
   },
   onmouseDown(e){
     document.onmousemove = this.onmouseMove.bind(this);
     document.onmouseup = this.onmouseUp.bind(this);
     this.disX = e.clientX - this.dom.offsetLeft;
     this.disY = e.clientY - this.dom.offsetTop;
   },
   onmouseMove(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';
   },
   onmouseUp(){
     document.onmousemove = null;
     document.onmouseup = null;
​
     manageCookie.set('left', this.newLeft)
     manageCookie.set('top', this.newTop)
   }
 }
 moveDome.init(document.getElementsByTagName('div')[0])

3.localStorage

早期只有cookie存储数据,造成了cookie的滥用,H5中规定了新的存储方式localStorage以及  sessionStorage

  • localStorage

    • length   本地存储数据的数量

    • key()    通过索引找到存储的数据

    • getItem()    通过键名取到本地存储的数据

    • setItem()    设置一个本地存储数据

    • removeItem() 删除一个本地存储数据

    • clear()      清空本地存储数据

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值