您可以通过在每次状态更改时设置 cookie 值并在页面加载时检查该 cookie 值以设置初始状态以匹配先前设置的 cookie 值来执行此操作:
添加此 CSS 以通过关闭使默认状态,因此如果所需的最终状态是关闭的,它最初不会显示为打开然后关闭:
.toggled_content {display: none;}
添加这个javascript:
<script type="text/javascript">
$(document).ready(function(){
function hideContent() {
$(".toggled_content").slideUp();
$("img.upmid").attr('src',"images/downmid.png");
}
function showContent() {
$(".toggled_content").slideDown();
$("img.upmid").attr('src',"images/upmid.png");
}
// set initial state based on cookie value
// assumes default state is closed
if (readCookie("updown") == "down") {
showContent();
}
$(".toggle_parent").toggle(function(){
hideContent();
createCookie("updown", "up", 30)
},function(){
showContent();
createCookie("updown", "down", 30);
});
});
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 eraseCookie(name) {
createCookie(name,"",-1);
}
</script>