在JavaScript中,可以通过创建一个div
元素并设置其样式来实现一个自定义的弹出确认框效果。以下是一个简单的示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Custom Confirm Box</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<button id="confirmBtn">Click me</button>
<div id="customConfirmBox" class="confirm-box">
<div class="confirm-box-content">
<p>Are you sure?</p>
<button id="yesBtn">Yes</button>
<button id="noBtn">No</button>
</div>
</div>
<script src="script.js"></script>
</body>
</html>
.confirm-box {
display: none;
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(0,0,0,0.5);
justify-content: center;
align-items: center;
}
.confirm-box-content {
background: white;
padding: 20px;
border-radius: 5px;
text-align: center;
}
document.getElementById('confirmBtn').addEventListener('click', function() {
document.getElementById('customConfirmBox').style.display = 'flex';
});
document.getElementById('yesBtn').addEventListener('click', function() {
alert('You clicked Yes!');
document.getElementById('customConfirmBox').style.display = 'none';
});
document.getElementById('noBtn').addEventListener('click', function() {
alert('You clicked No!');
document.getElementById('customConfirmBox').style.display = 'none';
});
div
。justify-content
和align-items
属性来确保确认框居中显示。display: none
。通过这种方式,你可以创建一个简单且灵活的自定义确认框,以满足不同的应用需求。
领取专属 10元无门槛券
手把手带您无忧上云