js如何让confirm弹窗居中
时间: 2023-09-10 22:05:14 浏览: 187
可以使用以下 JavaScript 代码让 confirm 弹窗居中:
```javascript
function centerConfirm() {
const confirmBox = document.querySelector('.confirm');
const screenWidth = window.innerWidth;
const screenHeight = window.innerHeight;
const confirmWidth = confirmBox.offsetWidth;
const confirmHeight = confirmBox.offsetHeight;
confirmBox.style.left = (screenWidth - confirmWidth) / 2 + 'px';
confirmBox.style.top = (screenHeight - confirmHeight) / 2 + 'px';
}
window.addEventListener('resize', centerConfirm);
```
其中,`.confirm` 是你的 confirm 弹窗的类名,`centerConfirm()` 函数用于居中弹窗,`window.addEventListener('resize', centerConfirm)` 则是在窗口大小改变时重新居中弹窗。
相关问题
js自定义confirm弹窗
在JavaScript中,可以通过创建一个包含自定义HTML和CSS样式的模态对话框来实现自定义confirm弹窗。
以下是一个简单的例子:
HTML代码:
```html
<div id="confirm-box">
<div class="confirm-header">确认操作</div>
<div class="confirm-message">您确定要执行此操作吗?</div>
<div class="confirm-buttons">
<button id="confirm-yes">是</button>
<button id="confirm-no">否</button>
</div>
</div>
```
CSS样式:
```css
#confirm-box {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.5);
display: none;
z-index: 9999;
}
.confirm-header {
font-size: 20px;
font-weight: bold;
text-align: center;
margin-top: 30px;
}
.confirm-message {
font-size: 16px;
text-align: center;
margin-top: 20px;
}
.confirm-buttons {
text-align: center;
margin-top: 30px;
}
.confirm-buttons button {
padding: 10px 20px;
background-color: #fff;
border: 1px solid #ccc;
border-radius: 4px;
margin-right: 20px;
cursor: pointer;
}
.confirm-buttons button:hover {
background-color: #f5f5f5;
}
```
JavaScript代码:
```javascript
// 获取模态对话框和按钮元素
var confirmBox = document.getElementById("confirm-box");
var confirmYes = document.getElementById("confirm-yes");
var confirmNo = document.getElementById("confirm-no");
// 确认按钮点击事件
confirmYes.addEventListener("click", function() {
// 执行确认操作
confirmBox.style.display = "none";
});
// 取消按钮点击事件
confirmNo.addEventListener("click", function() {
// 关闭模态对话框
confirmBox.style.display = "none";
});
// 显示模态对话框
function showConfirmBox(message) {
// 设置确认消息
document.querySelector(".confirm-message").innerHTML = message;
// 显示模态对话框
confirmBox.style.display = "block";
}
```
使用时,可以调用showConfirmBox方法,并传入确认消息作为参数:
```javascript
showConfirmBox("您确定要执行此操作吗?");
```
这样就可以弹出一个自定义的confirm弹窗,等待用户操作。
html,confirm弹窗的使用
HTML中的confirm弹窗可以用于显示一条消息,询问用户是否确认执行某个操作。用户可以点击“确定”或“取消”按钮进行选择。以下是使用confirm弹窗的示例代码:
```html
<!DOCTYPE html>
<html>
<head>
<title>Confirm弹窗示例</title>
</head>
<body>
<button onclick="showConfirm()">点击弹出confirm弹窗</button>
<script>
function showConfirm() {
// 显示confirm弹窗,并将用户的选择保存到result变量中
var result = confirm("确认要执行此操作吗?");
// 根据用户的选择,执行不同的操作
if (result == true) {
alert("用户选择了确定");
} else {
alert("用户选择了取消");
}
}
</script>
</body>
</html>
```
在这个示例中,我们通过调用JavaScript中的confirm()函数来显示confirm弹窗,将用户的选择保存到result变量中。然后根据用户的选择,执行不同的操作。需要注意的是,confirm弹窗会阻塞用户操作,因此应该仅在必要时使用。