我得到了这个 JS 脚本,它设置 cookie 并显示/隐藏 div
<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();">
<a href="#" onClick="hidePopup(); return false;">Turn Off</a></br></br>
<a href="#" onClick="showPopup(); return false;">Turn On</a>
<div id="popup" style="display:none">Hello! Welcome to my site. If you want to hide this message then click</div>
</body>
</html>
我需要有人,如果有人好心地向我解释一下,我该如何更改 cookie 值? (名称、过期等)以及如何将开/关按钮合并到 1 个按钮中,该按钮将完成切换显示/隐藏并相应地编辑 cookie 的工作。
最佳答案
要更改 cookie 的当前值,您可以使用相同的名称再次设置 cookie,该名称将与 cookie 的当前值重叠
对于第二个问题,您可以使用复选框进行开/关
function shoWhidePopup(el){
if(el.checked==true){
showPopup();
}else if(el.checked==false){
hidePopup();
}
}
在 html 中
<label>
<input type="checkbox" onclick="shoWhidePopup(this);" hidden>
<span style="appearance:button; -moz-appearance:button; -webkit-appearance:button;">show/hide</span>
</label>
关于javascript - JS cookie div 可见性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25656275/