一、COOKIE的封装函数

function setCookie(name,value,eDate){
  var oDate = new Date();
  oDate.setDate(oDate.getDate()+eDate);//alert(oDate.getSeconds()+eDate);
  document.cookie=name+'='+value+';expires='+oDate;
}
setCookie('ch','baaaa',1);
function getCookie(name){
  var arr=document.cookie.split('; ');
  var i=0;
  for(i=0;i<arr.length;i++){
    var arr2=arr[i].split('=');
    if(arr2[0]==name){
      return arr2[1];
    }
  }
return '';
}
function removeCookie(name){
  setCookie(name,'',-1);
}

二、应用

栗子一:记录上一次div的位置

先加载COOKIE的封装函数

window.onload=function(){
  var oDiv = document.getElementById('div1');
  var disX=0;
  var disY=0;

  var x=getCookie('x');
  var y=getCookie('y');
  if(x){
    oDiv.style.left = x+'px';
    oDiv.style.top = y+'px';
  }

  document.onmousedown=function(ev){
    var oEvent=ev||event;
    disX = oEvent.clientX-oDiv.offsetLeft;
    disY = oEvent.clientY-oDiv.offsetTop;
    document.onmousemove=function(ev){
      var oEvent=ev||event;
      var l = oEvent.clientX-disX;
      var t = oEvent.clientY-disY;
      var scrollTop = document.documentElement.scrollTop||document.body.scrollTop;
      var scrollLeft = document.documentElement.scrollLeft||document.body.scrollLeft;
      if(l>0&&l<document.documentElement.clientWidth-oDiv.offsetWidth&&t>0&&t<document.documentElement.clientHeight-oDiv.offsetHeight){
        oDiv.style.left = l+'px';
        oDiv.style.top = t+scrollTop+'px';
      }

    }
    document.onmouseup=function(){
      document.onmousemove=null;
      document.onmouseup=null;

      setCookie('x',oDiv.offsetLeft,1);
      setCookie('y',oDiv.offsetTop,1);
    }
  }

}

栗子二:记录上次登录的用户名以及删除

var oForm=document.getElementById('form1');
var oUser=document.getElementsByName('user')[0];
var oBtnClear=document.getElementsByTagName('a')[0];

oForm.onsubmit=function(){
  setCookie('user',oUser.value,1);
}
oUser.value=getCookie('user');
oBtnClear.onclick=function(){
  removeCookie('user');
  oUser.value='';
}

 

posted on 2013-12-17 12:04  狂流  阅读(205)  评论(0编辑  收藏  举报