Computer >> 컴퓨터 >  >> 프로그래밍 >> JavaScript

JavaScript에서 경고창(alert) 스타일을 변경하는 방법 — 커스텀 알림 상자 만들기

기본 alert() 상자는 스타일 변경이 불가능합니다

JavaScript의 기본 alert() 상자는 브라우저가 자체적으로 제공하는 내장 UI 요소입니다. 따라서 CSS나 JavaScript를 사용해도 폰트, 색상, 크기 등 디자인을 변경할 수 없습니다.

경고창의 스타일을 자유롭게 꾸미고 싶다면, 화면에 표시되는 커스텀 알림 상자(Custom Alert Box)를 직접 만들어 사용해야 합니다. 아래 예제에서는 JavaScript 라이브러리인 jQuery를 활용해 이를 구현합니다.

예제 코드

<!DOCTYPE html>
<html>
   <head>
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
      </script>
      <script>
         function functionAlert(msg, myYes) {
            var confirmBox = $("#confirm");
            confirmBox.find(".message").text(msg);
            confirmBox.find(".yes").unbind().click(function() {
               confirmBox.hide();
            });
            confirmBox.find(".yes").click(myYes);
            confirmBox.show();
         }
      </script>
      <style>
         #confirm {
            display: none;
            background-color: #514E61;
            color: #FFFFFF;
            border: 1px solid #aaa;
            position: fixed;
            width: 250px;
            left: 50%;
            margin-left: -100px;
            padding: 6px 8px 8px;
            box-sizing: border-box;
            text-align: center;
         }
         #confirm button {
            background-color: #48E5DA;
            display: inline-block;
            border-radius: 5px;
            border: 1px solid #aaa;
            padding: 5px;
            text-align: center;
            width: 80px;
            cursor: pointer;
         }
         #confirm .message {
            text-align: left;
         }
      </style>
   </head>
   <body>
      <div id="confirm">
         <div class="message">This is a warning message.</div>
         <button class="yes">OK</button>
      </div>
      <input type="button" value="Click Me" onclick="functionAlert();" />
   </body>
</html>

코드 동작 방식 살펴보기

1. 커스텀 함수(functionAlert)

functionAlert(msg, myYes) 함수는 전달받은 메시지(msg)를 #confirm

영역의 .message 요소에 넣고, 확인 버튼(.yes)이 클릭되면 상자를 숨긴 뒤 콜백 함수(myYes)를 실행하도록 구성되어 있습니다. 기존에 바인딩된 이벤트를 unbind()로 제거한 후 다시 바인딩하기 때문에, 버튼 클릭 이벤트가 중복 실행되는 문제도 방지할 수 있습니다.

2. CSS 스타일링

정리

표준 alert()는 어떤 방법으로도 스타일을 바꿀 수 없지만, 위처럼 <div> 요소와 jQuery를 조합한 커스텀 알림 상자를 사용하면 배경색, 버튼 디자인, 위치 등 원하는 대로 완전히 제어할 수 있습니다. 필요에 따라 애니메이션 효과나 오버레이 배경(모달 처리)을 추가하면 더욱 완성도 높은 UX를 구현할 수 있습니다.