JavaScript 原生三种弹窗方法详解

作者:像素漫游

时间:2026-10-30

浏览:293

本文介绍 JavaScript 中三种原生弹窗:alert、confirm 和 prompt 的基本用法与返回值。同时提供基于 DOM 操作的自定义弹窗代码示例,展示如何创建带有遮罩层的对话框,并说明其实现逻辑与注意事项。

文章目录

JavaScript 原生弹窗方法

JavaScript 提供了三种原生的弹窗方法,分别用于不同的交互场景。

第一种是 alert(),用于弹出警告信息,该函数没有返回值。例如:alert('第一行\n第二行'); 可以显示多行文本。

第二种是 confirm(),用于让用户做出选择(确定或取消),返回布尔值 true 或 false。例如:var result = confirm('是否删除!'); 可根据返回值判断用户操作。

第三种是 prompt(),用于弹出输入框,返回用户输入的字符串内容。例如:var value = prompt('输入你的名字:', '请在这里输入名字'); 第二个参数为默认值。

自定义弹窗实现示例

除了原生弹窗,开发者也可以自定义样式更美观的对话框。以下代码展示了如何实现一个简单的自定义弹窗,但代码可能存在待修正的问题,建议后续完善。


<script>
//window.confirm
//prompt
window.alert = function(title,str) 
{ 
var shield = document.createElement("DIV"); 
shield.id = "shield"; 
shield.style.position = "absolute"; 
shield.style.left = "0px"; 
shield.style.top = "0px"; 
shield.style.width = "100%"; 
shield.style.height = document.body.scrollHeight+"px"; 
//弹出对话框时的背景颜色 
shield.style.background = "#fff"; 
shield.style.textAlign = "center"; 
shield.style.zIndex = "25"; 
//背景透明 IE有效 
//shield.style.filter = "alpha(opacity=0)"; 
var alertFram = document.createElement("DIV"); 
alertFram.id="alertFram"; 
alertFram.style.position = "absolute"; 
alertFram.style.left = "50%"; 
alertFram.style.top = "50%"; 
alertFram.style.marginLeft = "-225px"; 
alertFram.style.marginTop = "-75px"; 
alertFram.style.width = "450px"; 
alertFram.style.height = "150px"; 
alertFram.style.background = "#ff0000"; 
alertFram.style.textAlign = "center"; 
alertFram.style.lineHeight = "150px"; 
alertFram.style.zIndex = "300"; 
strHtml = "<ul style=\"list-style:none;margin:0px;padding:0px;width:100%\">\n"; 
strHtml += " <li style=\"background:#DD828D;text-align:left;padding-left:20px;font-size:14px;font-weight:bold;height:25px;line-height:25px;border:1px solid #F9CADE;\">" + title + "</li>\n"; 
strHtml += " <li style=\"background:#fff;text-align:center;font-size:12px;height:120px;line-height:120px;border-left:1px solid #F9CADE;border-right:1px solid #F9CADE;\">" + str + "</li>\n"; 
strHtml += " <li style=\"background:#FDEEF4;text-align:center;font-weight:bold;height:25px;line-height:25px; border:1px solid #e85727;\"><input type=\"button\" value=\"确 定\" onclick=\"doOk()\" /></li>\n"; 
strHtml += "</ul>\n"; 
alertFram.innerHTML = strHtml; 
document.body.appendChild(alertFram); 
document.body.appendChild(shield); 
var ad = setInterval("doAlpha()",5); 
this.doOk = function(){ 
alertFram.style.display = "none"; 
shield.style.display = "none"; 
} 
alertFram.focus(); 
document.body.onselectstart = function(){return false;}; 
}
</script>

以上就是 JavaScript 三种弹窗的简要介绍与自定义实现示例,希望对大家有所帮助。

实用工具推荐

电子包浆

绿化、压缩、噪点和虚拟水印,自由调节做旧程度。

使用 ›
图片压缩

选择画质和输出格式,预览压缩前后的大小。

使用 ›
相关文章