자바스크립트_Javascript

자바스크립트: onclick 이벤트, 버튼을 클릭할 때마다 문자열과 배경 변경하기

coding-abc.tistory.com 2025. 8. 19. 16:08
반응형

아래 코드는 버튼을 클릭할 때마다 문자열과 배경을 변경하는 자바스크립트 코드입니다.

<!DOCTYPE html>
<html>
<head>
  <title>랜덤 문구 + 배경색 예제</title>
</head>
<body style="text-align:center; padding:50px;">
  <h2 id="msg">버튼을 눌러보세요 😀</h2>
  <button onclick="changeRandom()">클릭</button>

  <script>
    function changeRandom() {
      // 문구 배열
      const messages = [
        "안녕하세요!",
        "반가워요 😃",
        "오늘도 좋은 하루 되세요 🌸",
        "JavaScript 재미있죠?",
        "클릭해주셔서 감사합니다 🙏",
        "행운이 가득하길 바랍니다 🍀"
      ];

      // 랜덤 문구 선택
      const randomMsg = messages[Math.floor(Math.random() * messages.length)];
      document.getElementById("msg").innerHTML = randomMsg;

      // 랜덤 배경색 생성 (RGB 값 랜덤)
      const randomColor = `rgb(${Math.floor(Math.random()*256)}, 
                               ${Math.floor(Math.random()*256)}, 
                               ${Math.floor(Math.random()*256)})`;
      document.body.style.backgroundColor = randomColor;
    }
  </script>
</body>
</html>

 

자바스크립트: onclick 이벤트
자바스크립트: onclick 이벤트

반응형