Front/JS

코드로 배우는 JavaScript

잘잔디 2023. 3. 31. 11:27

HTML 계층구조 파악

  • 전체를 animation_canvas로 묶고 있고,
  • 이미지를 담당하는 slider_panel, text를 담당하는 slider_text_panel, 버튼을 담당하는 control_panel로 나뉘어져 있다.

슬라이딩 적용 방식

  1. 전체 이미지를 연결하여 width = 3000 ,height = 400으로 한 이미지 처럼 만든다.
  2. 출력창(animation_canvas)을 width = 600 , height = 400으로 설정하여 보이는 부분을 만든다.
  3. 1번의 이미지를 이동시켜 2번의 출력창에 보이게 하기 위해 600px단위로 묶어서 이동하도록 만든다.

button 적용 방식

  • 아래 사진처럼 클릭할 때 마다 적용되도록 보이게 하기 위해서 버튼 이미지 5개를 세로로 새워서 한칸씩 만 사용한 것이다.
  • 사용자가 클릭하여 활성상태가 되면 선택된 버튼 이미지가 위로 솟아서 파란 점이 보이도록 하는 것이다.

전체 코드

HTML

    <!DOCTYPE html>
<html>
<head>
    <title>sliding</title>
    <link rel='stylesheet' type='text/css' media='screen' href='main.css'>
    <script src = "https://code.jquery.com/jquery-1.10.2.js"></script>
    <script src='main.js'></script>
</head>
<body>
    <h1>Test Header</h1>
    <div class="animation_canvas">
        <div class="slider_panel">
            <img src="Desert.jpg" class="slider_image"/>
            <img src="Hydrangeas.jpg" class="slider_image"/>
            <img src="Jellyfish.jpg" class="slider_image"/>
            <img src="Koala.jpg" class="slider_image"/>
            <img src="Lighthouse.jpg" class="slider_image"/>
        </div>
        <div class="slider_text_panel">
            <div class="slider_text">
                <h1>Lorem ipsum</h1>
                <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
            </div>
            <div class="slider_text">
                <h1>Nulla eget</h1>
                <p>Nulla eget sapien mauris, ornare elementum elit.</p>
            </div>
            <div class="slider_text">
                <h1>Quisque eleifend</h1>
                <p>Quisque eleifend augue nec lacus lobortis porta.</p>
            </div>
            <div class="slider_text">
                <h1>Donec</h1>
                <p>Donec a ligula lectus, eu iaculis justo.</p>
            </div>
            <div class="slider_text">
                <h1>Vivamus scelerisque</h1>
                <p>Vivamus scelerisque mauris id nunc dictum sit amet.</p>
            </div>
        </div>
        <div class="control_panel">
            <div class="control_button"></div>
            <div class="control_button"></div>
            <div class="control_button"></div>
            <div class="control_button"></div>
            <div class="control_button"></div>
        </div>
    </div>
    <h1>Test Footer</h1>
</body>
</html>

CSS

* { margin:0px; padding:0px; }
/* Animation Canvas */
.animation_canvas  {
    width : 600px;height : 400px;
    overflow: hidden;/*600 x 400 밖으로 나오는 애들은 가린다.*/
    position : relative;
}
/* Slider Panel */
.slider_panel {
    width: 3000px; 
    position: relative;
    background-color: pink;
}
.slider_image {
    float : left; 
    width : 600px; height : 400px;
}
/* Slider Text Panel */
.slider_text_panel {   
    position: absolute;
    top: 200px;
    left: 50px;
}
.slider_text { 
    position:absolute;
    width: 250px; height: 150px; color:white;
}
/* Control Panel */
.control_panel  {
    position:absolute;
    top:380px; left : 270px;height:13px;
    overflow: hidden;
}
.control_button {
    width:12px; height: 46px;
    position:relative;
    float: left;
    cursor: pointer;
    background: url('point_button.png');
}
.control_button:hover { top:-16px; } /*마우스 가져다 대면 16px 올려서 활성 된 것 처럼 보임*/
.control_button.active { top:-31px; }/*마우스 클릭시 활성화 되어 파란 점이 보임*/

JavaScript

$(document).ready(function(){
    //슬라이더 움직여줌
    function moveSlide(index){
        //슬라이더 이동
        var willMoveLeft = -(index*600);
        //도착지점은 왼쪽(0,0)이므로 이동할 거리를 -방향으로 지정
        $('.slider_panel').animate({left:willMoveLeft},'slow');
        //control_button에 active클래스를 부여/제거합니다.
        $('.control_button[data-index=' + index + ']').addClass('active');
        $('.control_button[data-index!=' + index + ']').removeClass('active');
        
        //글자를 이동합니다
        //show()-문서객체를 크게 하며 보여준다.
        //hide()-문서객체를 작게 하여 사라진다.
        //effectMethod(event,callback)형식-해당효과가 완료된 후, 호출될 함수
        $('.slider_text[data-index=' + index + ']').show().animate({
            left: 0
        },'slow');//모든 내용이 겹쳐서(0,0)에 있으므로 그대로 보여주기만 하면 된다.
        $('.slider_text[data-index!=' + index + ']').hide('slow',function(){
            $(this).css('left',-300);
            //hide 함수가 수행한 후 수행될 기능 서술
        })
    }
    //초기 텍스트 위치 지정 및 data-index 할당
    $('.slider_text').css('left',-300).each(function(index){//css조작
        $(this).attr('data-index',index);//텍스트 각각 0~4까지 속성정보(attr메소드로) 추가됨.
    })
    //컨트롤 버튼의 클릭 핸들러 지정 및 data-index 할당
    $('.control_button').each(function(index){//5개의 버튼에 모두 적용하기 위해 each를 사용함.
        $(this).attr('data-index',index)//버튼 각각 0~4까지 속성정보(attr메소드로) 추가됨.
    }).click(function(){//버튼 클릭시에 이벤트 발생
        var index = $(this).attr('data-index');//index를 불러와서
        moveSlide(index);//moveSlide 실행
    });
    //초기 슬라이더 위치 지정
    var randomNumber = Math.round(Math.random()*4);//0~4
    moveSlide(randomNumber)
})

실행예시