因此,要做到这一点,最简单的方法(IMO)是创建一个容器,你的按钮+盒(您想隐藏)。你的按钮会一直保持。当页面加载时,我们将一个事件附加到您的按钮上,该事件将根据框的当前状态(如果它隐藏,显示它,如果它是可见的,隐藏它)显示和隐藏您的框。
很容易。
现在,你也想坚持网页加载/访问页面之间的可见光/隐藏状态。要做到这一点,你需要在用户的浏览器上添加一个cookie(注意,如果你的用户登录了或者其他的东西,你可以用另一种方式做到这一点 - 但是一个cookie是最简单的方法来完成它, t涉及将数据保存到数据库的服务器往返)。
为了做到这一点,我建议去使用jQuery Cookie Plugin,它的使用非常简单(正如你将在下面看到的那样),并且在处理cookie时会带来很多麻烦。每当用户点击按钮,并更改框的状态时,就会向用户的浏览器写入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>
是不是比它需要更复杂? – 2011-05-07 20:02:33
如果他想要将动画设置为一定高度以保持按钮可见,则可见使用将不起作用 - 但是,这可能不是最好的方式! – 2011-05-07 20:14:46