您可以使用本地 javascript 将状态保存在 cookie 中(不涉及服务器):
function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
function toggle_visibility(id, cookieName) {
var e = document.getElementById(id);
var visible;
if(e.style.display == 'block') {
e.style.display = 'none';
visible = false;
} else {
e.style.display = 'block';
visible = true;
}
if (cookieName) {
createCookie(cookieName, visible, 1);
}
}
然后,当你的页面被加载时,你可以在 DOM 加载完成后调用这个函数来恢复之前的状态:
function restore_visibility(id, cookieName) {
var visibility = readCookie(cookieName);
if (visibility == null) return; // no cookie
var e = document.getElementById(id);
if (visibility) {
e.style.display = 'block';
} else {
e.style.display = 'none';
}
}
您可以使用类似"contactFormVisible"
cookieName 的字符串。