jQuery: Сворачиваемые блоки

80

Небольшой пример демонстрирующий эффект сворачивания однотипных блоков (например постов в блоге или виджетов в сайдбаре) с помощью jQuery.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<div class="post">
    <div class="title">
        <h3><a href="" title="">Заголовок</a></h3>
        <p>Автор, 12.02.2010</p>
    </div>
    <div class="entry">
        <!-- Контент -->
    </div>
</div>
 
<div class="post">
    <div class="title">
        <h3><a href="" title="">Заголовок</a></h3>
        <p>Автор, 12.02.2010</p>
    </div>
    <div class="entry">
        <!-- Контент -->
    </div>
</div>
 
…

В данном примере присутствуют несколько постов. Сворачиваться будет их содержимое.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
.post {
    padding:10px 20px;
    position:relative;
    background:#eee;
    margin-bottom:20px
}
.inactive {
    color:#bbb
}
.post .title {
    position:relative;
    height:1%
}
.post .title h3 {
    font-size:1.4em
}
.post .title h3 a {
    text-decoration:none;
    color:#000
}
.inactive .title h3 a {
    color:#bbb
}
.post .title p {
    font-size:0.7em;
    font-style:italic;
    font-weight:bold;
    margin:0
}
.post .title span {
    position:absolute;
    right:0;
    top:30%;
    cursor:pointer;
    width:14px;
    height:14px;
    background:url(trigger.gif) no-repeat left bottom;
    display:block;
    font-size:0
}
#content .inactive .title span {
    background-position:left top
}
#content .post .entry {
    padding:10px 0
}

Span служит кнопкой для сворачивания и разворачивания блоков и добавляется с помощью js. Поэтому пользователи с отключенным js его не увидят.

1
2
3
4
5
6
7
8
9
$('.title').append('<span></span>');
$('.post span').each(function() {
   var trigger = $(this), state = false, el = trigger.parent().next('.entry');
   trigger.click(function(){
      state = !state;
      el.slideToggle();
      trigger.parent().parent().toggleClass('inactive');
   });
});