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

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

Alert mặc định không cho phép ảnh. Tạo custom alert box với HTML/CSS/JS.

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

<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<style>
#alertBox { 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; }
#alertBox img { max-width:100%; margin:10px 0; }
#alertBox button { padding:8px 20px; background:#2196F3; color:#fff; border:none; border-radius:4px; cursor:pointer; }
</style>
</head>
<body>
    <div id="alertBox">
        <div class="message">Đây là cảnh báo!</div>
        <img src="https://example.com/warning.png" width="120" alt="Warning"/>
        <button id="alertOk">OK</button>
    </div>
    <button onclick="showAlert()">Mở Alert</button>
    <script>
        function showAlert() {
            $('#alertOk').off().click(function(){ $('#alertBox').hide(); });
            $('#alertBox').show();
        }
    </script>
</body>
</html>