js中confirm自定义按钮文字
时间: 2023-07-27 13:19:16 浏览: 1011
JavaScript中原生的confirm()函数无法直接自定义按钮文字,但是我们可以通过一些技巧来实现。
一种比较常见的方法是使用CSS样式来隐藏原生的按钮,然后在confirm弹框中插入我们自己的HTML元素来模拟按钮,并通过JavaScript代码来控制按钮的点击事件。
以下是一个简单的实现例子:
HTML代码:
```
<div id="confirm-box">
<p>请确认您的选择</p>
<button id="confirm-ok">确定</button>
<button id="confirm-cancel">取消</button>
</div>
```
CSS代码:
```
#confirm-box button {
display: none;
}
```
JavaScript代码:
```
function showConfirm() {
var confirmBox = document.getElementById('confirm-box');
var confirmOk = document.getElementById('confirm-ok');
var confirmCancel = document.getElementById('confirm-cancel');
confirmBox.style.display = 'block'; // 显示自定义的confirm弹框
confirmBox.style.left = (window.innerWidth - confirmBox.offsetWidth) / 2 + 'px'; // 居中显示
confirmBox.style.top = (window.innerHeight - confirmBox.offsetHeight) / 2 + 'px';
// 模拟“确定”按钮的点击事件
confirmOk.onclick = function() {
// 用户选择了“确定”按钮
confirmBox.style.display = 'none'; // 隐藏confirm弹框
// 进行相应操作
};
// 模拟“取消”按钮的点击事件
confirmCancel.onclick = function() {
// 用户选择了“取消”按钮
confirmBox.style.display = 'none'; // 隐藏confirm弹框
// 进行相应操作
};
}
// 调用showConfirm函数以显示自定义的confirm弹框
showConfirm();
```
在这个例子中,我们使用CSS样式将原生的按钮隐藏起来,然后在confirm弹框中插入了我们自己的HTML元素来模拟按钮。最后,通过JavaScript代码来控制按钮的点击事件,并进行相应的操作。