因此,要做到这一点,最简单的方法 (imo) 是为您的按钮 + 框(您想要隐藏的)创建一个容器。您的按钮将始终保持不变。当页面加载时,我们会在您的按钮上附加一个事件,该事件将根据框的当前状态显示和隐藏您的框(如果它是隐藏的,则显示它,如果它是可见的,则隐藏它)。
很简单。
现在,您还希望在页面加载/页面访问之间保持可见/隐藏状态。要做到这一点,您需要在用户的浏览器上安装一个 cookie(旁注,如果您的用户已登录或其他方式,您可以通过其他方式执行此操作 - 但 cookie 是完成它的最简单的方法,并且没有t 涉及服务器往返以将数据保存到数据库)。
为了做到这一点,我建议去获取jQuery Cookie Plugin,它使用起来非常简单(如下所示),并且在处理 cookie 时可以省去很多麻烦。每次您的用户单击您的按钮并更改框的状态时,您都将向用户的浏览器写入一个 cookie 并存储框的当前状态。这样,当用户重新加载页面时,您将知道当前状态是什么(因为 cookie)。在下面的示例中,我将 cookie 设置为一年后过期,但您可以根据需要更改。
<div id="ShowHideContainer">
<p><a id="ShowHideButton">Click Here To Hide!</a></p>
<div id="ShowHideBox">text that gets shown and hidden, woo</div>
</div>
<script>
$(document).ready(function()
{
var $ShowHideBox = $('#ShowHideBox').hide(),
$ShowHideButton = $('#ShowHideButton');
/* Initialize the box based on the state of the cookie in the user's browser*/
initBox();
$('#ShowHideButton').click(function() {
if (boxVisible())
{
//the box is visible. lets hide it.
hideBox();
}
else
{
//the box is invisible. show it.
showBox();
}
});
function initBox()
{
//if the cookie says this is visible, and it's not...show it
if ( $.cookie('BoxVisible') && ! boxVisible() )
{
showBox();
}
//if the cookie says this is not visible, and it is...hide it
else if ( ! $.cookie('BoxVisible') && boxVisible() )
{
hideBox();
}
}
//check to see if the box is visible or not, currently
function boxVisible()
{
return $ShowHideBox.hasClass('hidden')? false : true;
}
//show the box, change the button text, and set the cookie
function showBox()
{
$ShowHideBox.slideUp(250).removeClass('hidden');
$ShowHideButton.html("Click Here to Hide!");
$.cookie('BoxVisible', 1, {expires: 365});
}
//hide the box, change the button text, and set the cookie
function hideBox()
{
$ShowHideBox.slideDown(250).addClass('hidden');
$ShowHideButton.html("Click Here to Show!");
$.cookie('BoxVisible', 0, {expires: 365});
}
});
</script>