使用JavaScript和Cookie隐藏块(并记住它)?

use*_*744 6 html javascript cookies hide

我想在我的网站上实现show-hidden div块,就像在stackoverflow.com上一样 - 当用户想把它自己隐藏在按钮"X"上时.可能已经有了现成的解决方案吗?我不是Javascript的诗句,非常感谢你的帮助!

图片:

ink*_*ink 4

这是一个简单的工作示例,无需使用任何外部库。您可以通过动画/设计来改进它。此外,这些 cookie 函数可以非常简单,但您将来可以使用它来设置布尔值。 更新:我添加了再次显示弹出窗口的功能(主要用于调试)。

<html>
<head>
<script type="text/javascript">
function setCookie (name, value, expires, path, domain, secure) {
    document.cookie = name + "=" + escape(value) +
    ((expires) ? "; expires=" + expires : "") +
    ((path) ? "; path=" + path : "") +
    ((domain) ? "; domain=" + domain : "") +
    ((secure) ? "; secure" : "");
}
function getCookie (name) {
    var cookie = " " + document.cookie;
    var search = " " + name + "=";
    var setStr = null;
    var offset = 0;
    var end = 0;
    if (cookie.length > 0) {
        offset = cookie.indexOf(search);
        if (offset != -1) {
            offset += search.length;
            end = cookie.indexOf(";", offset);
            if (end == -1) {
                end = cookie.length;
            }
            setStr = unescape(cookie.substring(offset, end));
        }
    }
    if (setStr == 'false') {
        setStr = false;
    } 
    if (setStr == 'true') {
        setStr = true;
    }
    if (setStr == 'null') {
        setStr = null;
    }
    return(setStr);
}
function hidePopup() {
    setCookie('popup_state', false); 
    document.getElementById('popup').style.display = 'none';
}
function showPopup() {
    setCookie('popup_state', null);
    document.getElementById('popup').style.display = 'block';
}
function checkPopup() {
    if (getCookie('popup_state') == null) { // if popup was not closed
        document.getElementById('popup').style.display = 'block';
    }   
}

</script>
</head>
<body onload="checkPopup();">
     <div id="popup" style="display:none">Hello! Welcome to my site. If you want to hide this message then click <a href="#" onclick="hidePopup(); return false;">[x]</a></div>
     <div>Some static text here.</div>
     <div>Bring me <a href="#" onclick="showPopup(); return false;">back</a> my popup!</div>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)