개발 기록

자바스크립트[기본 문법/버튼 이벤트] 본문

공부

자바스크립트[기본 문법/버튼 이벤트]

청군로 2021. 3. 3. 18:04

html에서 사용가능한 프로그래밍인 자바 스크립트를 배웠다.

 

변수는 메모리에 만들어진 공간을 말한다.

 

변수에 들어갈 수 있는 값의 종류에는 숫자, 문자, 논리형 크게 세 가지로 나눌 수 있는데,

변수 선언 시에는 앞에 variable을 뜻하는 var을 붙여준다. //자바 스크립트 뒤에는 세미콜론의 습관화!

 

문자를 선언할 때는 문자를 쌍 따옴표로 감싸줘야 한다.

 

 

onClick=""

//클릭했을 때 이벤트를 준다.

 

버튼을 이용하여 사진을 바꿀 수 있는 기능구현.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        #wrapper{
            width: 600px;
            height: 450px;
            margin: auto;

        }

        #wrapper img{
           width: 100%;
           height: 400px;
           object-fit: cover;

        }
        
        #consol{
            position: relative; /*자식에게 포지션이 명시되면 부모도 명시 되어야 함!*/
            width: 100%;
        }

        #consol img{
            width: 50px;
            height: 50px;
            background-color: gray;
        }
        /*포지션 앱솔루트를 이용하면 기준이 부모의 테두리가 된다.
        즉, rightBt의 부모는 consol이므로 consol의 오른쪽 벽에서 0px만큼 떨어진다는 뜻이 된다.*/
        .rightBt{
            position: absolute;
            right: 0px;
        }

        .leftBt{
            position: absolute;
            left: 0px;
        }

    </style>
    <script>
        //변수를 이용해서 이미지를 변경할 예정
        var i=1;
        function moveLeft() {
            i-=1;
            //사진이 5번까지 있어서 제한을 뒀다.
            if(i==0) i=5;
            //문서내의 #img안에 있는 src를 변경한다.
            document.querySelector("#img").src="../image/nba"+i+".jpg"
        }

        function moveRigth(){
            i+=1;
            if(i==6) i=1;
            document.querySelector("#img").src="../image/nba"+i+".jpg"
        }
    </script>
</head>
<body>
    <div id="wrapper">
        <img id="img" src="../image/nba1.jpg">
        <br>
        <div id="consol">
            <img class="leftBt" src="../image/left.png" onclick="moveLeft()">
            <img class="rightBt"src="../image/right.png" onclick="moveRigth()">
        </div>
    </div>
    </body>
</html>

 

 

'공부' 카테고리의 다른 글

자바스크립트[삼항연산자]  (0) 2021.03.05
자바스크립트[연산자]  (0) 2021.03.04
div와 span  (0) 2021.02.26
C언어 #4[구조체]  (0) 2021.01.23
C언어 #3[동적 할당]  (0) 2021.01.20
Comments