【问题标题】:How to get Javascript cookie to remember DIV state?如何让 Javascript cookie 记住 DIV 状态?
【发布时间】:2009-08-16 18:51:35
【问题描述】:

我有一个测试站点here(仍在开发中),我正在尝试让顶部的小通知在您单击关闭后保持隐藏状态。

目前我的脚本是这样的:

<style type="text/css">
<!--
.hide {
display:none;
}
.show {
display:block;
}
-->
</style>
<script type="text/javascript">
<!--
var state;
window.onload=function() {
obj=document.getElementById('alert');
state=(state==null)?'show':state;
obj.className=state;

document.getElementById('close').onclick=function() {
obj.className=(obj.className=='show')?'hide':'show';
state=obj.className;
setCookie();
return false;
}
}

function setCookie() {
exp=new Date();
plusMonth=exp.getTime()+(31*24*60*60*1000);
exp.setTime(plusMonth);
document.cookie='State='+state+';expires='+exp.toGMTString();
}

function readCookie() {
if(document.cookie) {
state=document.cookie.split('State=')[1];
}
}
readCookie();
//-->
</script> 

然后:

<div id="alert" class="show" style="float: left; width: 100%;"><div style="width: 80%; text-align:left; float:left;">Sorry for the downtime, we were experiencing some problems with our web host. Everything should be back to normal now =D</div> 
<div style="width: 18%; text-align:right; float:left; padding-right: 20px;"><a href='#' id="close">close</a></div> </div>

但它似乎不起作用。有什么想法吗?

提前致谢!

山姆

【问题讨论】:

    标签: javascript css cookies hide state


    【解决方案1】:

    首先,你需要修复readCookie,你调用split会返回“State=”之后的所有内容,这将存储在返回数组的第一个偏移量中,所以改为这样做:

    function readCookie() {
        if(document.cookie) {
            var tmp = document.cookie.split(';')[0];
            state = tmp.split('=')[1];
            alert(state);
        }
    }
    

    【讨论】:

    • 哦,是的,抱歉——我以为 Mage 先生先回答了。固定 =)
    • @sm - 这两个答案中的哪一个解决了您的问题?您应该“勾选”最有帮助的一项。如果他们都对您有帮助,您应该出于礼貌为他们投票 - 标准的 SO 礼仪。
    • 是的,抱歉 - 我的声望还不够(还...)
    【解决方案2】:

    对我来说,它确实有效(Firefox 3.5、Windows XP)。但在网站完成加载之前,div 不会消失。您可能希望首先将 div 设置为 style="hide",并在页面加载后显示。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-07
      • 1970-01-01
      • 2013-09-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-13
      • 2022-12-03
      相关资源
      最近更新 更多