웹페이지

JAVASCRIPT STEP 48 - STYLE 다양한 알고리즘 - 2

IT의 큰손 2023. 4. 28. 16:19
728x90

★ 알고리즘 6 

  • 보안키 입력패드를 구현

■ HTML 코드

<div id="box">
    <div id="secret">
        <input type="text" id="pw" readonly maxlength="4">
        <div id="digit">
            <input type="button" value="7" name="num">
            <input type="button" value="8" name="num">
            <input type="button" value="9" name="num">
            <input type="button" value="4" name="num">
            <input type="button" value="5" name="num">
            <input type="button" value="6" name="num">
            <input type="button" value="1" name="num">
            <input type="button" value="2" name="num">
            <input type="button" value="3" name="num">
            <input type="button" value="0" name="num">
            <input type="button" value="del" name="del">
            <input type="button" value="enter" name="enter">
            <div style="clear:both;"></div>
        </div>
    </div>
    <div id="desc">
        <h1>비밀번호 입력</h1>
        <h3>사용법</h3>
        <ol>
            <li>숫자 4자리를 입력한다.</li>
            <li>enter를 누른다.</li>
        </ol>
        <h3>구현할 것</h3>
        <ul>
            <li>숫자 버튼을 눌러 입력한다.</li>
            <li>del 버튼을 눌러 삭제한다.</li>
            <li>4자리 이상 입력이 되지 않는다.</li>
            <li>정답 암호 : 0425</li>
            <li>암호가 틀리면 붉게 변한다.</li>
            <li>암호가 맞으면 파랗게 변한다.</li>
            <li>3회 틀리면 작동이 불가능하다.</li>
            <li>상단 숫자키로 입력할 수 있다.</li>
            <li>우측 숫자키로 입력할 수 있다.</li>
            <li>백스페이스, Delete, Enter 키로 입력할 수 있다.</li>
        </ul>
    </div>
    <div style="clear:both;"></div>
</div>

■ CSS 코드

<style>
    #box {
        width: 890px;
        margin: 30px auto;
    }

    #secret {
        border: 1px solid #aaa;
        border-radius: 5px;
        background-color: #eee;
        float: left;
        width: 500px;
    }
    #desc {
        float: left;
        width: 350px;
        padding-left: 30px;
        color: #555;
    }

    #desc li {
        font-size: 16px;
        margin-bottom: 5px;
        font-family :fantasy;
    }

    #secret #pw {
        border: 1px dashed #aaa;
        font-size: 4.5em;
        color: #555;
        width: 390px;
        display: block;
        margin: 30px auto;
        padding: 10px;
        padding-left: 40px;
        letter-spacing: .85em;
        outline: none;
    }

    #secret #digit {
        padding-left: 23px;
        padding-bottom: 30px;
    }

    #secret #digit input {
        display: block;
        float: left;
        border: 1px solid #ccc;
        font-size: 5.5em;
        text-align: center;
        color: #555;
        padding: 10px;
        width: 140px;
        height: 140px;
        margin: 5px;
        text-shadow: -1px -1px 2px gray; 
        background: white;/*  linear-gradient(#ccc, white, #ccc); */
        outline: none;
    }

    #secret #digit input:nth-last-child(2)
        , #secret #digit input:nth-last-child(3) {
        font-size: 2.5em;
    }

</style>

■ JavaScript

<script>
    var num, pw, enter, del;
    var maxCount = 0;

    window.onload = function() {

        num = document.all.num;
        pw = document.all.pw;
        enter = document.all.enter;
        del = document.all.del;

        for (var i=0; i<num.length; i++) {

            num[i].onclick = function() {
                if (pw.value.length < 4) {
                    pw.value += event.srcElement.value;
                }
            };

        }



        del.onclick = function() {
            pw.value = pw.value.substr(0, pw.value.length-1);
            document.bgColor = "white";
        };

        enter.onclick = function() {
            if (pw.value == "0425") {
                alert("암호가 일치합니다.");
                document.bgColor = "#66b3ff";
            } else {
                alert("암호가 일치하지 않습니다.");
                document.bgColor = "#ff8080";

                if (maxCount >= 2) {
                    document.bgColor = "#bb0000";
                    del.onclick = null;
                    enter.onclick = null;
                }
                maxCount++;
            }

        };


    };

    window.onkeydown = function() {

        var c = event.keyCode;

        if (c == 49 || c == 97) {
            num[6].click();
        } else if (c == 50 || c == 98) {
            num[7].click();
        } else if (c == 51 || c == 99) {
            num[8].click();
        } else if (c == 52 || c == 100) {
            num[3].click();
        } else if (c == 53 || c == 101) {
            num[4].click();
        } else if (c == 54 || c == 102) {
            num[5].click();
        } else if (c == 55 || c == 103) {
            num[0].click();
        } else if (c == 56 || c == 104) {
            num[1].click();
        } else if (c == 57 || c == 105) {
            num[2].click();
        } else if (c == 48 || c == 96) {
            num[9].click();
        } else if (c == 13) {
            enter.click();
        } else if (c == 110 || c == 8 || c == 46) {
            del.click();
        }

    };




</script>

■ 실행 결과

틀린 암호 입력 시, 배경색 빨갛게 변하고, 틀렸다는 문구가 출력됨.
암호가 일치할 시, 맞았다는 문구와 함께 배경이 파란색으로 변함.

 

★ 알고리즘 7

  • 고양이/강아지를 생성 후 테이블에 넣는다.
  • 만들기 버튼을 눌러 고양이/강아지를 생성.
  • 드래그로 이동시켜 테이블에 넣는다.
  • 테이블에 넣어진 고양이/강아지는 더 이상 이동이 불가능
  • document.elementFromPoint(x, y)
  • document.elementsFromPoint(x, y)

■ HTML 코드

<h1>고양이/강아지 보관함</h1>

<table id="tbl1">
    <tr>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
    </tr>
</table>

<h2>만들기</h2>
<div>
    <input type="button" value="고양이 만들기" id="btncat">
    <input type="button" value="강아지 만들기" id="btndog">
</div>
<div id="holder"></div>

■ CSS 코드

<style>
     body {
     	margin: 30px;
     }
     #tbl1 { border: 1px solid black; border-collapse: collapse; width: 1250px; }
     #tbl1 td { border: 1px solid black; width: 250px; height: 188px; }
     #tbl1 td img {
         border-radius: 5px;
         display: block;
     }
     #holder {
         margin-top: 10px;
         border: 1px solid black;
         width: 250px; height: 188px;
     }
     .item {
         position: absolute;
         border-radius: 5px;
     }
 </style>

■ JavaScript

<script>

    let isDown = false;
    let x = 0;
    let y = 0;
    let item;

    document.getElementById('btncat').addEventListener('click', function() {
        create('cat');
    });

    document.getElementById('btndog').addEventListener('click', function() {
        create('dog');
    });

    function create(name) {
        document.getElementById('holder').innerHTML = '';

        let n =parseInt(Math.random()*5) + 1;

        const img = document.createElement('img');

        img.setAttribute('src', `images/${name}0${n}.jpg`);
        img.classList.add('item');

        document.getElementById('holder').appendChild(img);
    }

    window.addEventListener('mousedown', function(event) {
        if (event.target.classList.contains('item')) {
            isDown = true;
            x = event.offsetX;
            y = event.offsetY;
            item = event.target;
        }
    });
    window.addEventListener('mousemove', function(event) {
        if (isDown) {
            item.style.left = event.clientX - x + 'px';
            item.style.top = event.clientY - y + 'px';

            event.stopPropagation();
            return false;
        }
    });
    window.addEventListener('mouseup', function(event) {
        isDown = false;

        let td = getTd(event);

        if (td) {
            td.appendChild(event.target);
            event.target.classList.remove('item');
        }
    });

    function getTd(event) {

        //해당 포인트에 어떤 태그들이 존재하는지 확인
        const list = document.elementsFromPoint(event.clientX, event.clientY);

        for (let i=0; i<list.length; i++) {
            if (list[i].nodeName == 'TD') {
                return list[i];
            }
        }
    }



</script>

■ 실행 결과

고양이,강아지 만들기 버튼 클릭시, 이미지가 생성되고 상위 보관함에 이미지를 옮겨 원하는 상자 위치에 옮겨 넣을 수 있다.

 

★ 알고리즘 8

  • 텍스트를 입력하면 화면을 진동시키시오.

■ HTML

<h1>제목입니다.</h1>
<input type="text" id="txt1" autofocus>
<hr>
<h2>다른 내용입니다.</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Alias, molestias deserunt repudiandae quas odio quis incidunt? Esse unde cupiditate sed dolores ut natus corrupti, adipisci explicabo repudiandae quod dignissimos asperiores?</p>
<p>Excepturi consequatur architecto consequuntur impedit animi sint inventore rerum quas nemo officiis modi hic tenetur, sit aliquid earum! Ullam iusto, nam enim ea numquam atque a amet incidunt laboriosam est!</p>
<p>Eveniet obcaecati error ratione, ex iure laudantium distinctio itaque. Obcaecati amet, voluptatum fugit dignissimos repudiandae laboriosam ullam. Vitae perspiciatis veritatis qui repudiandae necessitatibus ab soluta saepe pariatur, blanditiis sit ipsam!</p>
<p>Eveniet ab totam consectetur! Possimus corporis ea quod quas debitis hic reprehenderit repellat? Velit quas totam officia in. Ratione, quasi! Molestiae tenetur laudantium maiores. Sit nesciunt distinctio minima nostrum dolorum.</p>


<h1>Table</h1>

<table id="tbl1">
    <tr>
    <td>Lorem, ipsum dolor.</td>
    <td>Facere, autem ut.</td>
    <td>Aliquid, veritatis repellat.</td>
    <td>Eaque, expedita amet?</td>
    <td>Ratione, dignissimos obcaecati!</td>
    </tr>
    <tr>
    <td>Provident, ducimus reprehenderit?</td>
    <td>Sunt, aspernatur dolorum?</td>
    <td>Eum, magnam distinctio?</td>
    <td>Animi, tempora quis.</td>
    <td>Dignissimos, rerum explicabo?</td>
    </tr>
    <tr>
    <td>Nulla, eum molestiae!</td>
    <td>Ipsum, a necessitatibus!</td>
    <td>In, numquam nam?</td>
    <td>Expedita, voluptas molestiae.</td>
    <td>Officiis, optio voluptatum?</td>
    </tr>
    <tr>
    <td>Ea, quis minus.</td>
    <td>Sint, autem perspiciatis.</td>
    <td>Vel, dignissimos blanditiis!</td>
    <td>Non, saepe ut?</td>
    <td>Perspiciatis, rem in?</td>
    </tr>
    <tr>
    <td>Odit, expedita provident?</td>
    <td>Aut, autem itaque.</td>
    <td>Ea, beatae consequatur!</td>
    <td>Libero, fugit ratione.</td>
    <td>A, recusandae nemo.</td>
    </tr>
    <tr>
    <td>Quis, rerum aperiam?</td>
    <td>Dolor, neque quaerat!</td>
    <td>Omnis, nihil. Aspernatur?</td>
    <td>Maiores, nobis sunt.</td>
    <td>Fuga, nulla voluptate?</td>
    </tr>
    <tr>
    <td>Debitis, sunt sed!</td>
    <td>Eum, reprehenderit. Fugiat?</td>
    <td>Dolorem, voluptatem adipisci!</td>
    <td>Expedita, ad perferendis.</td>
    <td>Eum, doloribus ut.</td>
    </tr>
    <tr>
    <td>Atque, quidem expedita.</td>
    <td>Animi, inventore maiores.</td>
    <td>Nostrum, ut rem!</td>
    <td>Accusamus, nisi corrupti.</td>
    <td>Voluptatem, natus maiores.</td>
    </tr>
</table>

■ CSS 코드

<style>
    body {
        margin: 30px;
    }
    #txt1 {
        font-size: 3em;
        width: 100%;
    }
    #tbl1 { border: 1px solid black; border-collapse: collapse; }
    #tbl1 td { border: 1px solid black; padding: 4px; width: 100px; }
</style>

■ JavaScript

<script>
    window.onload = function() {
        document.getElementById("txt1").onkeydown = function() {
            var m = [-5, 5, 0];

            document.body.style.transform = "translate(" + (m[parseInt(Math.random() * 2)]) + "px, " + (m[parseInt(Math.random() * 2)]) + "px)";
            setTimeout(function() {
                document.body.style.transform = "translate(" + (m[parseInt(Math.random() * 2)]) + "px, " + (m[parseInt(Math.random() * 2)]) + "px)";
            }, 5);
            setTimeout(function() {
                document.body.style.transform = "translate(0px, 0px)";
            }, 20);
        };
    };
</script>

■ 실행 결과

텍스트를 입력하면 화면이 흔들리는 효과

 

★ 알고리즘 9

  • 텍스트를 입력하면 화면을 진동시키시오.
  • 연타를 하면 배경이 점점 붉게 변합니다.
  • 마지막 타이핑 후 1초가 지나면 배경이 돌아옵니다.

■ HTML 코드

<h1>제목입니다.</h1>
<input type="text" id="txt1" autofocus>
<hr>
<h2>다른 내용입니다.</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Alias, molestias deserunt repudiandae quas odio quis incidunt? Esse unde cupiditate sed dolores ut natus corrupti, adipisci explicabo repudiandae quod dignissimos asperiores?</p>
<p>Excepturi consequatur architecto consequuntur impedit animi sint inventore rerum quas nemo officiis modi hic tenetur, sit aliquid earum! Ullam iusto, nam enim ea numquam atque a amet incidunt laboriosam est!</p>
<p>Eveniet obcaecati error ratione, ex iure laudantium distinctio itaque. Obcaecati amet, voluptatum fugit dignissimos repudiandae laboriosam ullam. Vitae perspiciatis veritatis qui repudiandae necessitatibus ab soluta saepe pariatur, blanditiis sit ipsam!</p>
<p>Eveniet ab totam consectetur! Possimus corporis ea quod quas debitis hic reprehenderit repellat? Velit quas totam officia in. Ratione, quasi! Molestiae tenetur laudantium maiores. Sit nesciunt distinctio minima nostrum dolorum.</p>


<h1>Table</h1>

<table id="tbl1">
    <tr>
    <td>Lorem, ipsum dolor.</td>
    <td>Facere, autem ut.</td>
    <td>Aliquid, veritatis repellat.</td>
    <td>Eaque, expedita amet?</td>
    <td>Ratione, dignissimos obcaecati!</td>
    </tr>
    <tr>
    <td>Provident, ducimus reprehenderit?</td>
    <td>Sunt, aspernatur dolorum?</td>
    <td>Eum, magnam distinctio?</td>
    <td>Animi, tempora quis.</td>
    <td>Dignissimos, rerum explicabo?</td>
    </tr>
    <tr>
    <td>Nulla, eum molestiae!</td>
    <td>Ipsum, a necessitatibus!</td>
    <td>In, numquam nam?</td>
    <td>Expedita, voluptas molestiae.</td>
    <td>Officiis, optio voluptatum?</td>
    </tr>
    <tr>
    <td>Ea, quis minus.</td>
    <td>Sint, autem perspiciatis.</td>
    <td>Vel, dignissimos blanditiis!</td>
    <td>Non, saepe ut?</td>
    <td>Perspiciatis, rem in?</td>
    </tr>
    <tr>
    <td>Odit, expedita provident?</td>
    <td>Aut, autem itaque.</td>
    <td>Ea, beatae consequatur!</td>
    <td>Libero, fugit ratione.</td>
    <td>A, recusandae nemo.</td>
    </tr>
    <tr>
    <td>Quis, rerum aperiam?</td>
    <td>Dolor, neque quaerat!</td>
    <td>Omnis, nihil. Aspernatur?</td>
    <td>Maiores, nobis sunt.</td>
    <td>Fuga, nulla voluptate?</td>
    </tr>
    <tr>
    <td>Debitis, sunt sed!</td>
    <td>Eum, reprehenderit. Fugiat?</td>
    <td>Dolorem, voluptatem adipisci!</td>
    <td>Expedita, ad perferendis.</td>
    <td>Eum, doloribus ut.</td>
    </tr>
    <tr>
    <td>Atque, quidem expedita.</td>
    <td>Animi, inventore maiores.</td>
    <td>Nostrum, ut rem!</td>
    <td>Accusamus, nisi corrupti.</td>
    <td>Voluptatem, natus maiores.</td>
    </tr>
</table>

■ CSS 코드

<style>
    body {
        margin: 30px;
    }
    #txt1 {
        font-size: 3em;
        width: 100%;
    }
    #tbl1 { border: 1px solid black; border-collapse: collapse; }
    #tbl1 td { border: 1px solid black; padding: 4px; width: 100px; }
</style>

■ JavaScript

<script>
    var color = 0;
    var timer = 0;
    var gap = 0;

    window.onload = function() {

        document.getElementById("txt1").onkeydown = function() {
            var m = [-5, 5, 0];

            document.body.style.transform = "translate(" + (m[parseInt(Math.random() * 2)]) + "px, " + (m[parseInt(Math.random() * 2)]) + "px)";
            setTimeout(function() {
                document.body.style.transform = "translate(" + (m[parseInt(Math.random() * 2)]) + "px, " + (m[parseInt(Math.random() * 2)]) + "px)";
            }, 5);
            setTimeout(function() {
                document.body.style.transform = "translate(0px, 0px)";
            }, 20);

            document.body.style.backgroundColor = "rgba(255,0,0," + color + ")";
            color += 0.01;
            gap = 0;

        };

    };

    timer = setInterval(function() {

        gap++;

        if (gap > 2) {
            gap = 0;
            timer = 0;
            color = 0;
            document.body.style.backgroundColor = "white";
        }

    }, 1000);
</script>

■ 실행 결과

텍스트창에 텍스트를 입력시, 화면이 흔들리고, 배경색이 점점 빨강색으로 변함.

 

728x90