jquery

[jQuery] 더보기 / 접기 구현하기

http://portfolio.wonpaper.net 2021. 5. 12. 18:31

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<style>
    .box {margin:20px auto;}
    .content {
        width:800px;
        padding:10px;
        border:1px solid #ddd;
    }
 
</style>
 
<div class="box">
    <div class="content">
        <span>글쓴이 : 강감찬</span>
        <div class="contentStr">오늘은 조은날 고고싱<br>동해물과 백두산이 마르고 닳도록</div>
    </div>
</div>
 
 
<div class="box">
    <div class="content">
        <span>글쓴이 : 이순신</span>
        <div class="contentStr"></div>
    </div>
</div>
cs

 

 

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
<script text="javascript/text">
    $(document).ready(function(){
 
        $('.box').each(function(){
            //var content = $(this).children('.content');
            var content = $(this).find('.contentStr');
 
            var content_txt = content.text();
            var content_html = content.html();
            var content_txt_short = content_txt.substring(0,100)+"...";
            var btn_more = $('<a href="javascript:void(0)" class="more">더보기</a>');
 
            
            $(this).append(btn_more);
            
            if(content_txt.length >= 100){
                content.html(content_txt_short)
                
            }else{
                btn_more.hide()
            }
            
            btn_more.click(toggle_content);
            function toggle_content(){
                if($(this).hasClass('short')){
                    // 접기 상태
                    $(this).html('더보기');
                    content.html(content_txt_short)
                    $(this).removeClass('short');
                }else{
                    // 더보기 상태
                    $(this).html('접기');
                    content.html(content_html);
                    $(this).addClass('short');
 
                }
            }
        });
    });
  </script>
cs

 

참고 : moollang.tistory.com/8