当前位置:首页 > JavaScript

js 实现alert

2026-04-06 17:51:53JavaScript

使用 alert 函数显示消息

在 JavaScript 中,alert 是一个全局函数,用于在浏览器中弹出一个警告对话框。以下是基本用法:

alert("这是一个警告消息");

执行上述代码会在浏览器中弹出一个对话框,显示消息“这是一个警告消息”,用户需要点击“确定”按钮才能关闭对话框。

自定义警告框样式

默认的 alert 对话框样式由浏览器决定,无法直接修改。如果需要自定义样式,可以模拟一个警告框:

function customAlert(message) {
    const alertBox = document.createElement("div");
    alertBox.style.position = "fixed";
    alertBox.style.top = "50%";
    alertBox.style.left = "50%";
    alertBox.style.transform = "translate(-50%, -50%)";
    alertBox.style.padding = "20px";
    alertBox.style.background = "white";
    alertBox.style.border = "1px solid #ccc";
    alertBox.style.borderRadius = "5px";
    alertBox.style.boxShadow = "0 0 10px rgba(0, 0, 0, 0.1)";
    alertBox.style.zIndex = "1000";

    const messageText = document.createElement("p");
    messageText.textContent = message;
    alertBox.appendChild(messageText);

    const closeButton = document.createElement("button");
    closeButton.textContent = "确定";
    closeButton.style.marginTop = "10px";
    closeButton.onclick = function() {
        document.body.removeChild(alertBox);
    };
    alertBox.appendChild(closeButton);

    document.body.appendChild(alertBox);
}

customAlert("这是一个自定义警告框");

使用 confirm 替代 alert

如果需要用户确认操作,可以使用 confirm 函数。它会返回一个布尔值,表示用户点击的是“确定”还是“取消”:

const result = confirm("你确定要执行此操作吗?");
if (result) {
    console.log("用户点击了确定");
} else {
    console.log("用户点击了取消");
}

使用 prompt 获取用户输入

如果需要用户输入信息,可以使用 prompt 函数:

js 实现alert

const userName = prompt("请输入你的名字", "默认名字");
if (userName !== null) {
    console.log(`用户输入的名字是: ${userName}`);
}

注意事项

  • alertconfirmprompt 会阻塞浏览器线程,直到用户关闭对话框。
  • 在现代 Web 开发中,通常推荐使用自定义模态框(如 Bootstrap Modal 或自定义实现)替代原生弹窗,以提供更好的用户体验和样式控制。

标签: jsalert
分享给朋友:

相关文章

js 实现vue模板

js 实现vue模板

实现 Vue 模板的 JavaScript 方法 通过原生 JavaScript 可以实现类似 Vue 的模板渲染功能,主要包括数据绑定、指令处理和模板解析。以下是核心实现思路: 数据绑定与…

js jquery

js jquery

jQuery 简介 jQuery 是一个快速、简洁的 JavaScript 库,简化了 HTML 文档遍历、事件处理、动画设计和 Ajax 交互。它兼容多种浏览器,提供易于使用的 API,使开发者能够…

js实现代码雨

js实现代码雨

实现代码雨效果 使用HTML5 Canvas和JavaScript可以轻松实现经典的代码雨效果。以下是完整的实现代码和说明: HTML结构 <!DOCTYPE html> <htm…

js实现路由

js实现路由

js实现路由的方法 在JavaScript中实现路由功能可以通过多种方式完成,以下是几种常见的方法: 使用原生JavaScript实现路由 通过监听window.onhashchange事件来实现基…

js 实现跳转

js 实现跳转

使用 window.location.href 进行跳转 通过修改 window.location.href 可以跳转到指定 URL,浏览器会加载新页面: window.location.hre…

js实现下拉刷新

js实现下拉刷新

监听触摸事件 通过监听 touchstart、touchmove 和 touchend 事件来检测用户下拉手势。记录触摸起始位置和移动距离。 let startY = 0; let currentY…