用Js控制cookie代码收藏

DATE: 2016-11-10 / VIEWS: 652

<HEAD>
  <TITLE> New Document </TITLE>
  <META NAME="Generator" CONTENT="EditPlus">
  <META NAME="Author" CONTENT="milk">
  <style type="text/css">
  body{
    font-family: verdana;
  }
  #tip{
    position: absolute;
    top: 250px;
    left: 100px;
    font: 2em;
    background: #3366FF;
  }
  </style>

  <script type="text/javascript">
  //创建cookie的函数
  function writeCookie ()
   {
        //创建一个时间对象,用于确定cookie保留时间
        var destoryTime = new Date();
        //cookie在24小时后销毁
        destoryTime.setTime(destoryTime.getTime() + 24 * 3600 * 1000);
        //转为GMT时间
        var expireTime = destoryTime.toGMTString();
        //写入cookie  
        document.cookie = "visited=true" + ";expires=" + expireTime + ";";
        //////创建提示窗口
        document.write("<div id='tip'>欢迎首次光临BlueIdea论坛,5秒之后您将返回论坛首页...</div>");
        setTimeout("backToMainPage()",5000);    
   }
  
   //返回函数
   function backToMainPage()
   {
     window.location.href = "http://bbs.blueidea.com";
   }
  var isCookieExist;
  //检查cookie是否存在
  isCookieExist = document.cookie.length;
  //若cookie不存在则调用函数写入
  if(!isCookieExist)
    writeCookie();
  //若存在则检测cookie值
  else
  {
    //取出cookie值
    var cookieContent = document.cookie;
    //取出cookie状态
    var checkStatus = "visited=";
    //查找是否存在字符串visited=
    var startIndex = cookieContent.indexOf(checkStatus);
    //若查找的值存在
    if(startIndex != -1)
    {
       //把位置锁定到"="的后面
       startIndex += checkStatus.length;
       //从'='后开始查找符号","
       var endIndex = cookieContent.indexOf(",",startIndex);
       if(endIndex == -1)
          endIndex = cookieContent.length;    
       //取出visited=后的字串
       var result = unescape(cookieContent.substring(startIndex,endIndex));
       if(result != "true")
          writeCookie();
       else
          document.write("<div id='tip'>欢迎再次来到BlueIdea论坛!</div>");
    }
    else
      writeCookie();
  }
  </script>
  
</HEAD>
<BODY>
  </body>