0

I have no clue what I'm doing wrong. It works it just shows the popup for a split second. Would a timeout option be better? Which part is the problem? I'm a little new to Javascript so I don't really know what to exactly look for.

<script language="javascript" type="text/javascript">
/** Create a html cookie and set expiry as a day. **/
function createCookie(name,value,days) {
   var date = new Date();
   date.setTime(date.getTime()+(days*24*60*60*1000));
   var expires = date.toGMTString();
   document.cookie = name+"="+value+"; expires="+expires+"; path=/";
}
/** Check if already a cookie has been created. **/
function readCookie(name) {
    var flag = 0;
    var dcmntCookie = document.cookie.split(';');
    for(var i=0;i < dcmntCookie.length;i++) {
        var ck = dcmntCookie[i];
        while (ck.charAt(0)==' ') {
            ck = ck.substring(1,ck.length);
        }
        if(ck) {
            cparts = ck.split('=');
            if (cparts[0] == name) flag=1;
        }              
    }     
    if(flag) { 
        return true; 
    } else {
        return false; 
    }  
}
/** Check if cookie exists else create a new one. **/
function checkCookie(name) {
    if (readCookie(name)) {
        document.getElementById('google').style.display = "none";
        document.getElementById('google').style.visibility = "hidden";
    }
    else createCookie(name,"cookie 4 the day",1); 
}
</script>
<script type="text/javascript">

function closeThisDiv()

{

var openDiv = document.getElementById('google');

openDiv.style.display = 'none';

}
</script>
<body onLoad="checkCookie('MyCookie')"
4

2 回答 2

0

我这样修复它:

创建 display:none 的 css 属性;对于#google

#google{display:none;}

然后切换代码的​​最后一部分以仅在他们没有 cookie 时显示,并创建 cookie。

/** Check if cookie exists else create a new one. **/
function checkCookie(name) {
    if (readCookie(name)) {

    }
    else document.getElementById('google').style.display = "inline";
         document.getElementById('google').style.visibility = "visibility";
         createCookie(name,"cookie 4 the day",1);

万一有人遇到这个问题。对我来说效果很好。

于 2013-02-15T22:17:21.010 回答
0

id="google"如果您的目标是从页面显示的一开始就隐藏元素(因此它永远不会显示),那么您应该添加一个 CSS 规则,该规则在 head 部分中加载,如下所示:

#google {display: none;}

或者,您应该向 HTML 本身添加一个样式元素:

<div id="google" style="display:none"></div>

由于您的代码当前正在编写,听起来它正在做它应该做的事情。它等待整个文档(包括图像)被加载,然后用id="google". 这意味着该项目将在页面加载时短暂显示,然后您的代码将隐藏它。

如果您无法修改 google 对象的 CSS 或 HTML,而您只是想尽快使用 javascript 隐藏它,并且 google 对象存在于您页面的 HTML 中(未以编程方式添加),那么您可以这样做:

<body>
other HTML here

<script>
// script that executes right before the /body tag
checkCookie("MyCookie")
</script>

</body>

这至少不会等待所有图像在隐藏之前加载。

于 2013-02-15T21:45:51.640 回答