본문 바로가기

HTML/Javascript 기초

[Javascript] 물고기들의 지역좌표 설정하기

버튼을 하나 만들어서 눌렀을 때 물고기가 정렬되는 프로그램을 작성해보자.

각각의 물고기들을 each()를 이용하여 css를 통해 정렬한다.

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>물고기 위치 구하기</title>
    <script src="../../js/jquery-3.5.1.min.js"></script>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        #parent1 {
            border: 1px solid black;
            position: absolute;
            width: 500px;
            height: 400px;
            left: 100px;
            top: 100px;
        }

        #info {
            border: 1px solid black;
            position: absolute;
            width: 500px;
            height: 30px;
            margin: 50px 0 0 100px;
        }

        .fish {
            position: absolute;
            width: 120px;
        }

        .fish p {
            position: absolute;
            margin-top: 20px;
            text-align: center;
            width: 100%;
        }

        #fish1 {
            left: 50px;
            top: 100px;
        }

        #fish2 {
            left: 150px;
            top: 200px;
        }

        #fish3 {
            left: 180px;
            top: 50px;
        }

        #fish4 {
            left: 350px;
            top: 200px;
        }

        #fish5 {
            left: 50px;
            top: 300px;
        }

        #arrage {
            float: right;
        }
    </style>
    <script>
        $(document).ready(function () {
            var left = 0;
            var top = 0;

            $("#arrange").click(function () {
                $(".fish").each(function () {
                    left += 50;
                    top += 50;
                    $(this).css({ left: left, top: top });
                });
            });
        });
    </script>
</head>

<body>
    <div id="info">
        <input type="button" id="arrange" value="arange">
    </div>
    <div id="parent1">
        <div id="fish1" class="fish">
            <p>1</p><img src="../../images/fish1.png">
        </div>
        <div id="fish2" class="fish">
            <p>2</p><img src="../../images/fish1.png">
        </div>
        <div id="fish3" class="fish">
            <p>3</p><img src="../../images/fish1.png">
        </div>
        <div id="fish4" class="fish">
            <p>4</p><img src="../../images/fish1.png">
        </div>
        <div id="fish5" class="fish">
            <p>5</p><img src="../../images/fish1.png">
        </div>
    </div>

</body>

</html>

 

728x90
반응형