JavaScript의 기본 alert()이나 confirm() 상자는 브라우저가 제공하는 네이티브 대화상자이기 때문에 이미지나 HTML 요소를 삽입할 수 없습니다. 따라서 확인 상자에 이미지를 표시하려면 HTML과 CSS, 그리고 jQuery(또는 순수 JavaScript)를 활용해 사용자 정의 모달 대화상자를 직접 구현해야 합니다.
아래 예제는 jQuery로 만든 커스텀 확인 상자입니다. 질문이 "축구를 좋아하시나요?"이므로 축구공 이미지가 함께 표시되도록 구성했습니다.
예제
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
function functionConfirm(msg, myYes, myNo) {
var confirmBox = $("#confirm");
confirmBox.find(".message").text(msg);
confirmBox.find(".yes,.no").unbind().click(function () {
confirmBox.hide();
});
confirmBox.find(".yes").click(myYes);
confirmBox.find(".no").click(myNo);
confirmBox.show();
}
</script>
<style>
#confirm {
display: none;
background-color: #91FF00;
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: 100px;
cursor: pointer;
}
#confirm .message {
text-align: left;
}
</style>
</head>
<body>
<div id="confirm">
<div class="message"></div>
<img src="https://upload.wikimedia.org/wikipedia/en/thumb/e/ec/Soccer_ball.svg/120px-Soccer_ball.svg.png" width="150" height="110" />
<button class="yes">Like!</button>
<button class="no">No, I Like Cricket!</button>
</div>
<button onclick='functionConfirm("Do you like Football?", function yes() {
alert("Yes")
}, function no() {
alert("no")
});'>submit</button>
</body>
</html>코드 설명
- #confirm 영역: 화면 중앙에 고정(position: fixed)된 커스텀 대화상자로, 메시지 영역과 이미지, 두 개의 버튼을 포함합니다. 기본적으로
display: none;으로 숨겨져 있다가 필요할 때만 표시됩니다. - functionConfirm() 함수: 인자로 전달받은 메시지를
.message영역에 출력하고, 버튼 클릭 이벤트를 바인딩한 뒤 상자를 화면에 보여줍니다. 버튼을 클릭하면 상자가 사라지면서 각각myYes,myNo콜백 함수가 실행됩니다. - submit 버튼: 클릭하면
functionConfirm()이 호출되어 이미지가 포함된 확인 상자가 열리고, 선택 결과에 따라 "Yes" 또는 "no" 알림이 표시됩니다.
이처럼 커스텀 대화상자를 직접 구현하면 이미지뿐 아니라 아이콘, 링크, 스타일링된 버튼 등 원하는 UI 요소를 자유롭게 구성할 수 있습니다. 디자인 일관성이 중요한 프로젝트라면 네이티브 대화상자 대신 이러한 방식을 활용해 보세요.