노력이 좋아서

<step27>'js_변수선언, 함수선언'

zoaseo 2022. 4. 26. 10:51

1) 05variable.html

<!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>
</head>
<body>
    <script>
        let name;
        let admin;
        name = 'John'
        admin = name;
        alert(admin);
    </script>
</body>
</html>

2) 06variable.html

<!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>
</head>
<body>
    <h1>자바스크립트로 내용 입력하기</h1>
    <p></p>
    <script>
        let h1Text = document.querySelector('h1').innerHTML; 
        console.log(h1Text);
        let pNode = document.querySelector('p');
        pNode.innerHTML = '안녕하세요';
    </script>
</body>
</html>

3) 07prompt.html

<!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>
</head>
<body>
    <script>
        let age = prompt('나이를 입력하세요');
        //age를 숫자형으로 변경한 값을 result에 할당
        let result = Number(age);
        console.log(result);
        console.log(typeof result);
    </script>
</body>
</html>

4) 08confirm.html

<!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>
</head>
<body>
    <script>
        //alert : 메세지를 보여줌
        //prompt : 사용자에게 텍스트를 입력하도록함
        //확인을 누르면 입력한 문자열을 반환하고, 취소 또는 esc를
        //누르면 null을 반환합니다.
        //confirm : 사용자가 확인 또는 취소를 선택하도록함
        //확인을 누르면 true 취고를 누르면 false를 반환합니다.
        let isBoss = confirm("당신이 주인인가요?")
        console.log(isBoss);
    </script>
</body>
</html>

5) 09function.html

<!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>
</head>
<body>
    <script>
        
        //함수 선언문 방식
        //function 함수명(매개변수1, 매개변수2){
        //      return 반환값;
        //}
        //함수 선언문은 호이스팅됨
        //함수 정의하기전에 호출이 가능함
        
        document.write(add(7,9)+'<br>');
        document.write(add(578,54789));
        console.log(namename);
        function add(a,b){     //function은 호이스팅이기 때문에 아래에서 써도 전체 적용이 된다.
            return a + b;
        }
        function consolePrint(){
            console.log('함수를 실행했어요');
        }
        var namename = 'aaaaaa';   //var도 호이스팅이지만 undefined값이 담긴다.
        let result = consolePrint();
        console.log(result);
        
        //기본 매개변수값 (added in ES6)
        //전달하지 않은 매개변수의 디폴트값으 설정할 수 있음
        
        function showMessage(message, from = '그린'){
            console.log(`메세지는 ${message}이고 보낸 사람은 ${from}이다.`);
        }
        showMessage('안녕하세요','404호');
        
        //스코프: 변수의 유효범위
        //블럭안에서 선언하면 로컬변수(지역변수) 블럭밖에서 선언하면 글로벌변수(전역변수)
        //var 스코프는 함수 스코프
        //let 스코프는 블럭 스코프
        // var, let, const 구분
        // 1.var 재선언가능, 호이스팅됨(변수 선언부), 재할당 가능, 함수 스코프
        // 2.let 선언가능, 호이스팅되지않음, 재할당 가능, 블럭스코프
        // 3.const 선언과 동시에 할당, 호이스팅되지않음, 재할당안됨, 블럭스코프
        
        let userName = 'bella';
        function print(){
            let userAge = 30;
            var variable3 = 'aaaa'
            console.log(userName);
            console.log(userAge);
        }
        {
            var variable1 = 'abc';
            let variable2 = 'deg';
        }
        console.log(variable1);
        // console.log(variable2);
        // console.log(variable3);
        print();
        
        //리턴 값
        //리턴이 없는 경우 return undefined가 생략된 것임.
        
        //함수표현식
        //자바스크립트에서는 함수도 객체로 취급함.
        
        let sayHi = function(a,b){
            alert('Hello' + a + b + '도 안녕~!!!');
        };
        sayHi('영희','철수');

        //화살표함수 (Arrow function)
        //이름없는 함수를 간단하게
        let sayHi2 = () => alert('Hello'); //한줄일 때는 {}생략가능
        sayHi2();
    </script>
</body>
</html>

6) 10style.html

<!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>
        div { width: 1000px; height: 500px; background: yellow;}
    </style>
</head>
<body>
    <div></div>
    <button onclick="chBackground('pink')">pink색상</button>
    <button onclick="chBackground('rgb(255,0,0)')">red색상</button>
    <button onclick="chBackground('rgb(0,0,255)')">blue색상</button>
    <button onclick="chBackground('rgb(0,255,0)')">green색상</button>
    <button onclick="bgColorView()">배경색상알기</button>
    <script>
        //선택한 요소의 css속성값을 반환하기
        //1.style.속성명 (인라인 스타일로 작성된 값만 반환)
        //2.window.getComputedStyle(선택한 요소).getPropertyValue('스타일 속성명')
        //(내부 스타일 속성값을 반환)
        //div의 배경색을 pink로 변경
        function chBackground(bgcolor){
            document.querySelector('div').style.background = bgcolor;    
            document.querySelector('div').innerHTML = `${bgcolor}입니다.`;
            console.log(document.querySelector('div').style.background);
        }
        function bgColorView(){
            let div = document.querySelector('div');
            let style = window.getComputedStyle(div);
            console.log(style);
            alert(style.getPropertyValue('background-color'));
        }
    </script>
</body>
</html>

7) 11classList.html

<!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>
        * { margin: 0; padding: 0; box-sizing: border-box;}
        #header {
            background: #eee;
            height: 80px;
            overflow: hidden;
            transition: 0.5s;
        }
        #header.on {
            height: 180px;
        }
        ul {
            display: flex;
        }
        li {
            padding: 20px;
            line-height: 40px;
        }
        #submenuBg {
            height: 100px;
            background: tomato;
        }
    </style>
</head>
<body>
    <div id="header">
        <ul>
            <li onmouseenter="addOn()" onmouseleave="removeOn()">list1</li>
            <li>list2</li>
            <li>list3</li>
            <li>list4</li>
        </ul>
        <div id="submenuBg"></div>
    </div>
    <script>
        //li에 마우스를 올리면 header라는 id를 가진 요소의 클래스 on을 지정
        function addOn(){
            document.querySelector('#header').classList.add('on');
        }
        function removeOn(){
            document.querySelector('#header').classList.remove('on');
        }
    </script>
</body>
</html>

8) 12classListtoggle.html

<!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>
        div {
            width: 100%;
            height: 300px;
            background: pink;
        }
        div.on {
            background: yellow;
        }
    </style>
</head>
<body>
    <button onclick="chBackground()">클릭하세요</button>
    <div></div>
    <script>
        function chBackground(){
            document.querySelector('div').classList.toggle('on');
        }
    </script>
</body>
</html>