JavaScript

버튼을 클릭하면 요소가 생성되어 떨어지는 기능 구현 - 자바스크립트(Java Script)

그레이트현 2024. 7. 4. 09:37
반응형

돈이 비처럼 떨어지는 상상함


코드 실행

 

See the Pen money rain by Wi daehyeon (@widaehyeon) on CodePen.


HTML 코드

<div class="container">
    <div class="box" id="box"></div>
    <div class="button-container">
        <button id="createButton">생성</button>
        <button id="resetButton">초기화</button>
    </div>
</div>

 


CSS 코드

body {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
    margin: 0;
    background-color: #f0f0f0;
}

.container {
    text-align: center;
}

.box {
    width: 300px;
    height: 300px;
    background-color: white;
    border: 2px solid #333;
    position: relative;
    overflow: hidden;
}

.button-container {
    margin-top: 20px;
}

.money {
    position: absolute;
    font-size: 1.5rem;
    animation: fall 1s linear forwards;
}

@keyframes fall {
    0% {
        top: -20px;
        opacity: 0;
    }
    100% {
        top: var(--end-position);
        opacity: 1;
    }
}

button {
    margin: 5px;
    padding: 10px 20px;
    font-size: 16px;
    cursor: pointer;
}

`@keyframes`를 활용해 위에서 아래로 떨어지면서, 투명한 상태에서 점점 불투명한 상태로 변하는 기능을 구현

 

css `var()` 함수를 사용해 top의 값을 동적으로 부여 


JavaScript 코드

document.addEventListener('DOMContentLoaded', function() {
    const createButton = document.getElementById('createButton');
    const resetButton = document.getElementById('resetButton');
    const box = document.getElementById('box');

    createButton.addEventListener('click', createMoney);
    resetButton.addEventListener('click', resetMoney);

    function createMoney() {
        const boxRect = box.getBoundingClientRect();
        const money = document.createElement('div');
        money.classList.add('money');
        money.textContent = '💵';

        const x = Math.random() * (boxRect.width - 20);
        const y = Math.random() * (boxRect.height - 20);

        money.style.left = `${x}px`;
        money.style.setProperty('--end-position', `${y}px`);

        box.appendChild(money);
    }

    function resetMoney() {
        box.innerHTML = '';
    }
});

1) 생성 버튼 클릭이벤트

`document.getElementById()`를 사용해 createButton을 선택

`addEventListener('click', createMoney)`을 사용해 createButton을 누를 때마다 createMoney() 함수를 실행

2) 돈이 떨어질 위치 지정

`Math.random()`과 `getBoundingClientRect()`를 활용해 상자안에서 랜덤 하게 돈이 떨어질 위치를 정한다.

3) 돈이 떨어질 위치를 스타일로 적용

top 속성의 경우 `@keyframes` 애니메이션을 적용시켜야 하기 때문에 `var()`를 사용해 동적인 값을 넘겨준다.

`Element.style.setProperty`를 통해 css변수 '--end-position'에 값을 할당해 동적인 값을 css에 넘겨준다.


 

반응형