A. Cookie
Cookie:用于服务器自动完成发送给浏览器,由浏览器自动的存储起来,下次自动的发送出来。
1.Cookie具有保质期
2.每个浏览器的cookie文件不同
3.Cookie的限制
1) 存储大小限制:最大4096字节
2) 数量限制:
i:大多数浏览器只允许每个站点存储20个Cookie;
ii:有些浏览器对所有站点的Cookie总数有限制,通常300个。
3)Cookie默认情况会随着Http请求发送到后台服务器,但有些请求不需要Cookie,比如:js、css、图片等
4.满足同源策略
1)Domain 子域拿不到主域的Cookie值,只有当前域及其子域下拿得到。
2)path
复制代码
B. Cookie的属性值
domain 域名
path 路径
max-age 缓存时间 ms 以格林时间为基础
Expires 2018-12-08
复制代码
var oDate = new Date();//中国的标准事件
oDate.setDate(oDate.getDate() + 3);
document.cookie = 'age=18;max-age=1000';
复制代码
document.cookie = 'name=kiwi;expires=' + oDate;
复制代码
document.cookie = 'age=19;max-age=1000';
//覆盖之前的age,如果域或路径不同则不覆盖
复制代码
document.cookie = 'job=ui;expires=' + oDate +';path=/';
复制代码
封装一个简易的Cookie函数
var manageCookie = {
setCookie : function(name, value, time){
document.cookie = name + '=' + value + ';max-age' + time;
return this;
},
removeCookie : function(name){
//用cookie的时间过期来移除cookie值
return this.setCookie(name, '', -1);
},
getCookie : function(name, callback){
//document.cookie样式举例:color=red; age=27;
var allCookieArr = document.cookie.split(';');
//allCookieArr样式举例:[" color=red", " age=27"]
for(var i = 0;i < allCookieArr.length; i ++){
var itemCookieArr = allCookieArr[i].split('=');
if(itemCookieArr[0] == name){
callback(itemCookieArr[1]);
return this;
}
}
return this;
}
}
复制代码
链式调用
manageCookie
.setCookie('color','red',1000)
.setCookie('name','kiwi',20000)
.setCookie('age','27',30000)
.removeCookie('name')
.getCookie('age',function(data){
console.log(data);
});
复制代码
应用--记录小方块的位置
var oDemo = document.getElementById('demo');
var drag = {
//dom : oDeme;
init : function(dom){
this.dom = dom;
//给 drag 添加了属性 dom 方便后续引用
this.bindEvent();
//把这个 this 保存下来
var _this = this;
manageCookie.getCookie('newLeft' ,function(data){
//这里的 this 指向 window 的,所以要用保存下来的 _this 指向 drag
_this.dom.style.left = data + 'px';
}).getCookie('newTop' ,function(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;
//给 drag 添加了属性 disX 方便后续引用
this.disY = e.clientY - this.dom.offsetTop;
//给 drag 添加了属性 disY 方便后续引用
},
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, 1000).setCookie('newTop', this.newTop, 1000);
}
}
drag.init(oDemo);
复制代码