JavaScript의 기본 alert() 함수는 오직 텍스트만 표시할 수 있습니다. 브라우저에서 제공하는 기본 경고창은 이미지나 HTML 요소를 삽입할 수 없기 때문에, 경고창 안에 이미지를 보여주려면 커스텀 알림 박스(Custom Alert Box)를 직접 만들어야 합니다.
다행히 jQuery와 약간의 CSS만 활용하면 어렵지 않게 구현할 수 있습니다. 아래 예제는 버튼을 클릭했을 때 나타나는 사용자 정의 경고창 안에 메시지와 이미지를 함께 표시하는 방법을 보여줍니다.
예제: 이미지가 포함된 커스텀 경고창
아래 코드를 실행하고 'Click Me' 버튼을 클릭해 보세요. 화면 중앙에 경고창이 나타나며, 안내 메시지와 이미지가 함께 표시됩니다. 'OK' 버튼을 누르면 경고창이 닫힙니다.
<!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: #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>
<img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSNjyHBjM74KLxvROpx34zsT4zPzMWHMHz4zzJwAtemXGglsjtA"
width="120" height="70"/>
</div>
<input type="button" value="Click Me" onclick="functionAlert();" />
</body>
</html>코드 동작 원리
1. functionAlert() 함수
functionAlert()는 커스텀 경고창을 제어하는 핵심 함수입니다. #confirm