只在第一次访问时显示div(饼干?)

dam*_*mon 4 html javascript cookies

我正在尝试在用户第一次访问我的网站时显示div.我很确定我是通过使用cookies来实现这一点的,我的经验有限,并且我很难理解.我在网上找到的大多数教程都只谈到让cookie让用户输入类似名字的东西,并让它在以后回忆起来,这根本不是我想要的.我只是希望cookie检查用户之前是否已访问过我的网站,如果没有,则显示通常隐藏的div.

这是我尝试过但未能开始工作的东西.

HTML:

<head>
   <script type="text/javascript" src="annoy.js"></script>
   <script type="text/javascript" src="scripts.js"></script>
</head>

...
<body>
    <div id="overbox3">
         <div id="infobox3">
              <p>This is the cookie box</p>
              <br />
              <p>it should only show once </p>
              <br/><br/>
         </div><!-- end infobox3 --> 
    </div> <!-- end overbox3 -->
</body>
Run Code Online (Sandbox Code Playgroud)

CSS(因为这很好用,所以并不相关):

#overbox3 {
         position: fixed;
         top: 0px;
         left: 0px;
         width: 100%;
         height: 100%; 
         background: rgba(64, 64, 64, 0.5);
         z-index: 999999;
         display: none;
    }

    #infobox3 {
        margin: auto;
        position: absolute;
        left: 35%;
        top: 20%;
        height: 300px;
         width: 400px;
        background-color: white;
        border: 1px solid red;
    }
Run Code Online (Sandbox Code Playgroud)

scripts.js的相关内容:

function popbox3() {
    $('#overbox3').toggle();
}
Run Code Online (Sandbox Code Playgroud)

而我假设的是问题,annoy.js的内容:

    function GetCookie(name) {
        var arg=name+"=";
        var alen=arg.length;
        var clen=document.cookie.length;
        var i=0;

        while (i<clen) {
            var j=i+alen;
                if (document.cookie.substring(i,j)==arg)
                    return "here";
                i=document.cookie.indexOf(" ",i)+1;
                if (i==0) 
                    break;
        }

        return null;
    }

    var visit=GetCookie("COOKIE1");

    if (visit==null){
    var expire=new Date();

    popbox3();

    expire=new Date(expire.getTime()+7776000000);
    document.cookie="COOKIE1=here; expires="+expire;
}
Run Code Online (Sandbox Code Playgroud)

根据我的理解,cookie应该仅在用户未访问时调用函数popbox3(),这将切换隐藏div的显示.但截至目前,没有任何工作.任何澄清或帮助将不胜感激.提前致谢.

Bar*_*mar 6

你的cookie代码看起来很好.您需要在文档就绪处理程序中运行它,以便在切换DIV之前等待文档加载:

$(function() {
    var visit=GetCookie("COOKIE1");

    if (visit==null){
        popbox3();
    }
    var expire=new Date();
    expire=new Date(expire.getTime()+7776000000);
    document.cookie="COOKIE1=here; expires="+expire;
}
Run Code Online (Sandbox Code Playgroud)

我还将cookie设置为无条件,这样每次访问该站点都会缩短过期时间.