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

Cách thay đổi style nút bấm trên alert box JavaScript

Alert box mặc định không cho phép style. Phải tạo custom alert box.

Ví dụ Custom Alert với nút style đen/vàng

<!DOCTYPE html>
<html>
<head>
<style>
.alert-overlay { display:none; position:fixed; inset:0; background:rgba(0,0,0,0.5); z-index:1000; }
.alert-box { position:fixed; top:50%; left:50%; transform:translate(-50%,-50%); background:#000; color:#FCD116; padding:24px; border-radius:8px; width:90%; max-width:300px; text-align:center; box-shadow:0 8px 30px rgba(0,0,0,0.3); }
.alert-box button { background:#fff; color:#000; border:4px solid #aaa; border-radius:12px; padding:8px 20px; cursor:pointer; font-weight:bold; }
.alert-box button:hover { background:#FCD116; }
</style>
</head>
<body>
    <button onclick="showAlert()">Mở Alert</button>
    <div class="alert-overlay" id="alertOverlay">
        <div class="alert-box">
            <div class="message">Cảnh báo tùy chỉnh!</div><br>
            <button onclick="hideAlert()">OK</button>
        </div>
    </div>
    <script>
        function showAlert() { document.getElementById('alertOverlay').style.display='block'; }
        function hideAlert() { document.getElementById('alertOverlay').style.display='none'; }
        document.getElementById('alertOverlay').onclick = e => { if(e.target.id==='alertOverlay') hideAlert(); };
    </script>
</body>
</html>