본문 바로가기

JavaScript

[JavaScript] jQuery insertAfter(), insertBefore()

728x90
반응형

insertAfter() - 지정한 요소 뒤에 새로운 요소를 삽입

A.insertAfter(B) – B 뒤에 A를 추가

insertBefore() – 지정한 요소의 시작 부분에 내용을 삽입

A.insertBefore(B) – B 앞에 A를 추가

 

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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>광고, 갤러리</title>
<style type="text/css">
   *{
      margin: 0px;
      padding: 0px;
   }
   #content{
      width: 200px;
      margin: 20px;
   }
   #content .page{
      text-align: right;
      margin: 5px;
   }
   #content .page button{
      background: lightblue;
      color: white;
      width: 20px;
      height: 20px;
      overflow: hidden;
      border: none;
      line-height: 1.5;
   }
   #content .pic{
      width: 150px;
      height: 150px;
      border: 3px solid blue;
      overflow: hidden;
   }
</style>
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
</head>
<body>
<script type="text/javascript">
   $(document).ready(function(){
      var total=$(".pic > div").length// 4
      var curr=1;
      $(".pageInfo > span:first").text(curr);
      $(".pageInfo > span:last").text(total);
      $(".nextBtn").click(function(){
         curr++;
         if(curr>total){
            curr=1;
         }
         $(".pageInfo > span:first").text(curr);
         $(".pic div:first").insertAfter(".pic div:last");
      });
      $(".prevBtn").click(function(){
         curr--;
         if(curr<1){
            curr=total;
         }
         $(".pageInfo > span:first").text(curr);
         $(".pic div:last").insertBefore(".pic div:first");
      });
   });
</script>
   <div id="content">
      <div class="page">
         <span class="pageInfo">
            <span></span> / <span></span>
         </span>
         <button class="prevBtn">&lt; 이전</button>
         <button class="nextBtn">&gt; 다음</button>
      </div>
      <div class="pic">
         <div><img alt="1번째 사진" src="images/1.png"></div>
         <div><img alt="2번째 사진" src="images/2.png"></div>
         <div><img alt="3번째 사진" src="images/3.png"></div>
         <div><img alt="4번째 사진" src="images/4.png"></div>
      </div>
   </div>
</body>
</html>
cs

 

 

 

728x90
반응형