Просто думая о том, что вам нужно, первое, что вам нужно сделать, это дать каждому из ваших разделов «обертки» идентификатор. Этот идентификатор идентифицирует каждый переключаемый раздел в просмотрах страниц. Он не обязательно должен совпадать с атрибутом id
, но, скорее всего, будет проще, если идентификатор оболочки совпадает со значением атрибута id
соответствующего элемента div.wrapper
.
Затем, если вы хотите, чтобы все разделы были видны изначально, ваш файл cookie может хранить список идентификаторов разделов, которые скрыты . Таким образом, отсутствие cookie означает, что нет скрытых разделов, поэтому все разделы видны изначально.
Каждый раз, когда пользователь скрывает раздел, вы обновляете значение cookie, чтобы включить идентификатор вновь скрытого раздела. Каждый раз, когда пользователь отображает раздел, вы обновляете значение cookie, чтобы исключить идентификатор видимого раздела.
Наконец, при загрузке страницы вы перебираете идентификаторы в файле cookie, скрывая перечисленные разделы.
Вот код, который поможет вам начать работу:
<!DOCTYPE html>
<html lang="en">
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="jquery.cookie.js"></script>
<script type="text/javascript">
jQuery.fn.slideFadeToggle = function(speed, easing, callback) {
return this.animate({opacity: 'toggle', height: 'toggle'}, speed, easing, callback);
};
/**
* \returns an array of section IDs
*/
function getHiddenSectionIDs()
{
var arr = ($.cookie('hidden_section_ids') || '').split(',');
for (var i = 0; i < arr.length; ++i) {
arr[i] = $.trim(arr[i]);
if (arr[i].length <= 0)
arr[i] = null;
}
return arr;
}
function setHiddenSectionIDsCookie(hiddenSectionIDs)
{
var str = '';
for (var i = 0; i < hiddenSectionIDs.length; ++i) {
var id = hiddenSectionIDs[i];
if (id !== null)
str += ',' + id;
}
$.cookie('hidden_section_ids', str);
}
function toggle(t, updateCookie) {
var t = $(t);
var parent = t.parent();
// toggle hidden div
parent.find('.toggle').slideFadeToggle(400, function(){
// determine which image to use if hidden div is hidden after the toggling is done
var imgsrc = ($(this).is(':hidden')) ? 'http://i47.tinypic.com/vg0hu0.gif' : 'http://i45.tinypic.com/281tsle.gif';
// update image src
t.attr('src', imgsrc );
if (updateCookie || updateCookie === undefined) {
var hiddenSectionIDs = getHiddenSectionIDs();
if (parent.find('.toggle').is(':hidden'))
hiddenSectionIDs.push(parent.attr('id'));
else {
for (var i = 0; i < hiddenSectionIDs.length; ++i) {
var id = hiddenSectionIDs[i];
if (id == parent.attr('id'))
hiddenSectionIDs[i] = null;
}
}
setHiddenSectionIDsCookie(hiddenSectionIDs);
}
});
}
$(document).ready(function(){
var hiddenSectionIDs = getHiddenSectionIDs();
for (var i = 0; i < hiddenSectionIDs.length; ++i) {
var id = hiddenSectionIDs[i];
if (id !== null) {
var section = $('#' + hiddenSectionIDs[i]);
if (section) {
toggle(section.find('.hide'), false);
}
}
}
$('.hide').click(function(){
toggle(this);
});
});
</script>
</head>
<body>
<div id="section-1" class="wrapper">
<img class="hide" src="http://i45.tinypic.com/281tsle.gif" /> Header Text 1
<div class="toggle">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</div>
</div>
<p>
<div id="section-2" class="wrapper">
<img class="hide" src="http://i45.tinypic.com/281tsle.gif" /> Header Text 2
<div class="toggle">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</div>
</div>
</p>
</body>
</html>
Это далеко не классное / отполированное решение, но я проверил его, и оно работает.
Я использовал этот плагин cookie jQuery .