본문 바로가기

Programming/국비학원

220728 - 제이쿼리 - 플러그인 제작

  • 객체
  •  

    <script>
        var product={
            name:'냉장고',
            price:195000,
            type:'양문형',
        };
        function abc(){
            alert(this.name); //오류-> 객체 밖이므로 객체 이름 명명 필수 (product.name)
        }
    </script>
</head>
<body>
    <h2 onclick="abc();">제품</h2>
</body>

 

 

  • bind() : 함수, 객체 연결

    <script>
        var product={
            name:'냉장고',
            price:195000,
            type:'양문형',
        };
        var result=abc.bind(product); //abc 함수와 product 객체 연결
        function abc(){
            alert(this.name);  //냉장고
        }
    </script>
</head>
<body>
    <h2 onclick="result();">제품</h2>
</body>

 

 

  • extend(a,b) : 객체 통합 ~jQuery~

    <script src="../jQuery/js/jquery-3.6.0.min.js"></script>
    <script>
        var product={
            name:'냉장고',
            price:195000,
            type:'양문형',
        };
        var result=abc.bind(product); 
        function abc(){
            alert(this.name); 
        }
        var pcode={
            code:'ss1234',
            number:123
        };
        $.extend(product,pcode);  //객체 확장 (product으로 통합)
        console.log(product);
        alert(product.number);  //123
    </script>
</head>
<body>
    <h2 onclick="result();">제품</h2>
</body>

 

 

  • 객체 교체

    <script src="../jQuery/js/jquery-3.6.0.min.js"></script>
    <script>
        var wh={
            width:500,
            height:700
        };
        var ab={
            width:300,
            height:200
        };
        $.extend(wh,ab);  //같은 속성 -> ab값을 wh값으로 교체, 통합함
        console.log(wh); 
        //alert(wh.width);
    </script>
</head>
<body>
</body>

 

 

ex. 기존 이용했던 플러그인도 객체 속성 교체했음


            $('a[rel="colorbox"]').colorbox({
                transition:'fade',
                opacity:0.8,
                onOpen:function(){ //창 뜰 때
                    alert('7월에 출시된 신제품입니다');
                },
                onClosed:function(){
                    alert('한정 재고 상품입니다');
                }
            });

=> 기존 플러그인 default값이 입력한 속성값으로 교체됨

 

 

  • 배열
  • Array.from: 배열 복제

    <script src="../jQuery/js/jquery-3.6.0.min.js"></script>
    <script>
        var arr1=[10,20,30];
        arr1.push(40); //원본 배열 크기 변경
        console.log(arr1);  //4

        var arr2=[10,20,30];
        arr3=Array.from(arr2); //배열 복제
        arr3.push(50); //arr2는 변경되지 않음 -
        console.log(arr2); //3

        var arr4=[10,20,30];
        var arr5=arr4.concat(60); //arr4 변경되지 않음
        console.log(arr4); //3
    </script>
</head>
<body>
</body>

 

 

 

플러그인 만들기

1 css 파일을 제공할 것인가
2 플러그인 적용할 대상 태그는 무엇인가 
3 어떤 메서드를 제공할 것인가 ex. .colorbox()
4 어떤 옵션을 제공할 것인가 ex.opacity, transition, onOpen 등

사용자 중심적으로 만들 것

 

 

 

  • reverse.js
  • js

$.fn.chulsu=function(options){  //자바스크립트에서 속성값 받는 매개변수
    $(this).css('color','white');
    $(this).css('background','black') 
}

 

 

  • html

    <script src="js/jquery-3.6.0.min.js"></script>
    <script src="js/reverse.js"></script>
    <script>
        $(function(){
            $('h1').chulsu();
        });
    </script>
</head>
<body>
    <h1>길동이의 홈페이지</h1>
    <p>플러그인 제작 활용</p>
</body>

 

 

 

  • pivot.js
  • js
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
79
80
81
82
83
84
85
$.fn.pivot=function(options){ //메소드
    //변수 선언
    var $target=$(this); //이미지프레임을 target으로 지정
    var $items=$target.children(); //이미지를 item으로 지정
    var $container=$target.wrap('<div></div>').parent()
    //이미지프레임을 감싸는 부모 container 생성
    //target이 div로 wrap되고, 그 target의 부모가 container이 됨
    //parent() 미추가 시 div로 wrap된 target이 container가 됨
    var option={
        width:500,
        height:450
    };
    
    //옵션 처리
    $.extend(option,options)//새 options 값이 기존 option 대체 (option으로 통합)
 
    //스타일 지정
    $target.css({  //이미지 프레임
        width:$items.length*option.width,  //이미지 개수 * 대상 요소 너비 
        height:option.height,  //대상 요소 높이
        position:'absolute'
    });
    $items.css({  //이미지
        width:option.width,
        height:option.height,
        float:'left'
    });
    $container.css({
        width:option.width,
        height:option.height,
        position:'relative',
        overflow:'hidden',
    });
 
    //★이벤트 연결 (플러그인 동작: 드래그하고 놓으면 반대쪽으로 슬라이드 이동)
    var originLeft=0//원위치
    var oldLeft=0//왼쪽으로 드래그할 거리
    var nowPos=0//이미지 인덱스
    var isDown=false//마우스 다운 여부
 
    $target.on({
        mousedown:function(event){
            isDown=true;
            oldLeft=originLeft=event.clientX; //처음 마우스 누른 X좌표를 두 변수에 전달
            event.preventDefault();
        },
        mousemove:function(event){
            if (isDown){
                var distance=oldLeft-event.clientX; //mousedown 시작점-실시간 x좌표=드래그 거리
                oldLeft=event.clientX; //마우스무브 중인 실시간 x좌표를 시작점으로 넘김
                //드래그에 따른 움직임 구현
                $target.animate({
                    left:'-='+distance
                },0); //곧바로
                $target.stop(true); //clearqueue ???
            }
            event.preventDefault();
        },
        mouseup:function(event){ //마우스 놓았을 때 animate
            //내부 함수 선언
            function movePosition(direction){
                //위치 선정
                var changePos=nowPos+direction; //현재 인덱스+direction으로 인덱스 변경
                if(changePos>=0&&changePos<$items.length){ //인덱스 0~4
                    nowPos=changePos;
                }
            }
 
            //요소의 1/4 이상 드래그 -> pivot 구현
            if (originLeft-event.clientX>option.width/4){ //처음 누른 x좌표-실시간 x좌표
                movePosition(+1);
            }else if(originLeft-event.clientX<-option.width/4){
                movePosition(-1);
            }
 
            //타겟 움직임 구현
            $target.animate({
                left:-nowPos*option.width  //-(인덱스*이미지너비)
            },'slow');
            
            isDown=false;
            event.preventDefault();
        }
    });
}
cs

 

 

  • html
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
    <script src="js/jquery-3.6.0.min.js"></script>
    <script src="js/pivot.js"></script>
    <script>
        $(function(){
            $('#pivot_slider').pivot();
        });
    </script>
</head>
<body>
    <div id="pivot_slider">
        <div class="slider_text">
            <h2>Koala</h2>
            <img class="slider_image" src="../images/Koala.jpg" alt="">
            <p>유대목 코알라과에 속하는 포유류. 현지에서는 네이티브베어(native bear)라고 한다</p>
        </div>
        <div class="slider_text">
            <h2>Desert</h2>
            <img class="slider_image" src="../images/Desert.jpg" alt="">
 
            <p>강수량이 적어서 식생이 보이지 않거나 적고, 인간의 활동도 제약되는 지역</p>
        </div>
        <div class="slider_text">
            <h2>Lighthouse</h2>
            <img class="slider_image" src="../images/Lighthouse.jpg" alt="">
 
            <p>항로 표지의 하나. 바닷가나 섬 같은 곳에 탑 모양으로 높이 세워 밤에 다니는 배에 목표, 뱃길, 
위험한 곳 따위를 알려 주려고 불을 켜 비추는 시설</p>
        </div>
        <div class="slider_text">
            <h2>Jellyfish</h2>
            <img class="slider_image" src="../images/Jellyfish.jpg" alt="">
 
            <p>해파리는 대체로 투명하며, 갓 둘레에 많은 촉수를 가지고 있다. 촉수에는 자세포(쏘기세포)가 있어 
동물분류학상 자포동물(刺胞動物)문에 속한다.</p>
        </div>
        <div class="slider_text">
            <h2>Penguins</h2>
            <img class="slider_image" src="../images/Penguins.jpg" alt="">            
 
            <p>조류 펭귄목 펭귄과 동물을 통틀어 이르는 말. 펭귄과의 바닷새로서 남반구에 6속 18종이 있다. 곧추 서서
 걸으며 헤엄치기에 알맞게 날개가 지느러미 모양이고 앞다리의 날개깃은 변형되어 있다. </p>
        </div>
    </div>
</body>
cs