我想在我的网站上实现 show-hidden div block ,就像在 stackoverflow.com 上一样 - 当用户想要隐藏它时,他自己将其放在按钮“X”上。可能已经有了现成的解决方案?我不精通 Javascript,非常感谢您的帮助!
最佳答案
这是不使用任何外部库的简单工作示例。你可以用你的动画/设计来改进它。此外,这些用于 cookie 的函数可以非常简单,但您将来可以使用它来设置 bool 值。 更新:我添加了再次显示弹出窗口的功能(主要用于调试)。
<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>
关于javascript - 使用 JavaScript 和 cookie 隐藏 block (并记住它)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8546800/