项目中的一些危险操作经常需要popconfirm或者视口级别的二次确认弹窗,我们可以使用dialog或者window.condirm
但是dialog使用成本有点高,而window.condirm不能修改样式和位置;
我想这样使用
const async sameAct = ()=>{
if(await confirm()){
console.log("操作完成")
}else{
console.log("您已放弃本次操作")
}
}
那就这样封装它吧
export const localConfirm = (title: string = '', message: string = ''): Promise<boolean> => {
return new Promise((resolve) => {
const tipTitle = title || '是否确认转移所有者?';
const tipMessage = message || '转移所有者权限后,将失去对该草稿的所有权,只能查看该草稿';
// 创建对话框
const dialog = document.createElement('div');
dialog.style.cssText = `
position: fixed;
width: 100%;
height: 100%;
z-index: 1000;
top: 0;
left: 0;
background: rgba(0, 0, 0, 0.5);
backdrop-filter: blur(3px);
display: flex;
justify-content: center;
align-items: center;
`;
// 设置内容
dialog.innerHTML = `
<div style="background-color: #131313; border: 1px solid #5e5e5e; padding: 40px 40px 100px; font-size: 16px; position: relative;">
<div style="display: flex; align-items: center;">
<div style="margin-right: 20px; width: 25px; height: 25px; line-height: 25px; text-align: center; border-radius: 50%; color: #faad14; border: 2px solid #faad14;">!</div>
<div style="font-size: 20px; color: #e0e0e0;">${tipTitle}</div>
</div>
<div style="font-size: 14px; margin-left: 46px; margin-top: 10px; margin-bottom: 10px; color: #b4b4b4;">${tipMessage}</div>
<div style="position: absolute; bottom: 40px; right: 40px;">
<button id="confirmNo" style="margin-right: 10px; cursor: pointer; padding: 8px 16px; border: 1px solid #99999980; color: #fff">取消</button>
<button id="confirmYes" style="cursor: pointer; padding: 8px 16px; color: #fff; border: 1px solid #99999980;">确认</button>
</div>
</div>
`;
document.body.appendChild(dialog);
// 获取按钮元素
const confirmYes = dialog.querySelector('#confirmYes') as HTMLButtonElement;
const confirmNo = dialog.querySelector('#confirmNo') as HTMLButtonElement;
// 鼠标悬停样式处理
const addHoverEffect = (button: HTMLButtonElement) => {
button.addEventListener('mouseover', () => {
button.style.color = '#24d824';
button.style.borderColor = '#24d824';
});
button.addEventListener('mouseout', () => {
button.style.color = '#fff';
button.style.borderColor = '#99999980';
});
};
// 清理对话框及事件监听
const cleanup = () => {
dialog.remove();
};
// 绑定按钮事件
confirmYes.addEventListener('click', () => {
cleanup();
resolve(true);
}, { once: true });
confirmNo.addEventListener('click', () => {
cleanup();
resolve(false);
}, { once: true });
// 添加悬停效果
addHoverEffect(confirmYes);
addHoverEffect(confirmNo);
});
};