如果您想要一个向后兼容的解决方案,您可以在可用时将状态存储在 localStorage 中,否则存储在 cookie 中。如果您不想使用 cookie,您可以将标题状态附加到菜单中每个链接的哈希片段中,然后从document.location.href
加载下一页时读取状态。我为下面的 localStorage/cookie 版本编写了一些代码。不过,在某些方面,我认为哈希片段解决方案可能会更好(即使它使您的链接 URL 更丑陋),因为如果有人使用您的啤酒选择器,然后在一小时后返回该页面,也许您不希望当时自动扩展标题。
$(document).ready(function(){
function store_toggle_state(state) {
if (typeof(Storage) !== "undefined") {
localStorage["quick-brew-header"] = state;
} else {
// No localStorage, so use a cookie
// Alternatively, you could store in URL
// $.map($(".quick-brew-container a"), function (link) {
// $(link).attr("href", $(link).attr("href").split("#")[0] + "#" + state;
// });
document.cookie = "quick-brew-header=" + state;
}
}
function get_toggle_state() {
var state = false;
if (typeof(Storage) !== "undefined") {
if ("quick-brew-header" in localStorage) {
state = localStorage["quick-brew-header"];
}
} else {
// Alternatively, read state from document.location.href if it's there
var cookies = document.cookie.split("; ");
$.map($.makeArray(cookies), function (cookie_str) {
var cookie = cookie_str.split("=");
if (cookie[0] == "quick-brew-header") {
state = cookie[1];
}
});
}
if (state === "true" || state === "false") {
state = (state === "true");
}
return state;
}
function header_off() {
store_toggle_state(false);
$(".zone-preface-wrapper").animate({height:40},40);
}
function header_on() {
store_toggle_state(true);
$(".zone-preface-wrapper").animate({height:165}, 40);
}
var show_at_load = get_toggle_state();
if (show_at_load) {
header_on();
} else {
header_off();
}
// What happens on even/odd clicks depends on if we showed the header at page load
$(".quick-brew-header").toggle(show_at_load ? header_off : header_on,
show_at_load ? header_on : header_off);
});