Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Cách hiển thị ảnh trong hộp confirm (confirm box) bằng JavaScript

Confirm box mặc định không hỗ trợ ảnh. Cần tạo custom confirm box với HTML/CSS/JS (dùng jQuery trong ví dụ gốc).

Ví dụ (Custom Confirm với ảnh)

<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<style>
#confirm { display:none; position:fixed; top:50%; left:50%; transform:translate(-50%,-50%);
    background:#fff; padding:20px; border:1px solid #ddd; border-radius:8px; width:300px; text-align:center; box-shadow:0 4px 20px rgba(0,0,0,0.2); z-index:1000; }
#confirm img { max-width:100%; height:auto; margin:10px 0; }
#confirm button { margin:5px; padding:8px 16px; border:none; border-radius:4px; cursor:pointer; }
.btn-yes { background:#4CAF50; color:#fff; }
.btn-no { background:#f44336; color:#fff; }
</style>
</head>
<body>
    <div id="confirm">
        <div class="message"></div>
        <img src="https://upload.wikimedia.org/wikipedia/en/e/ec/Soccer_ball.svg" width="120" alt="Football"/>
        <button class="btn-yes">Thích!</button>
        <button class="btn-no">Không, thích Cricket!</button>
    </div>
    <button onclick="showConfirm()">Hỏi xem</button>
    <script>
        function showConfirm() {
            $('#confirm .message').text("Bạn có thích bóng đá?");
            $('#confirm .btn-yes').off().click(function(){ alert("Yes"); $('#confirm').hide(); });
            $('#confirm .btn-no').off().click(function(){ alert("No"); $('#confirm').hide(); });
            $('#confirm').show();
        }
    </script>
</body>
</html>

Tương tự cho Alert box với ảnh (chỉ có nút OK).