当前位置:首页 > JavaScript

js实现提示框

2026-04-04 01:19:17JavaScript

使用 alert() 方法实现基础提示框

alert() 是浏览器内置的全局方法,用于显示简单的文本提示框。

alert('这是一个基础提示框');

使用 confirm() 方法实现确认提示框

confirm() 方法显示一个带有确定和取消按钮的对话框,返回布尔值。

js实现提示框

const result = confirm('确定要删除吗?');
if (result) {
    console.log('用户点击了确定');
} else {
    console.log('用户点击了取消');
}

使用 prompt() 方法实现输入提示框

prompt() 方法显示一个带有输入框的对话框,返回用户输入的字符串。

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

自定义HTML提示框

通过HTML和CSS创建更灵活的提示框。

js实现提示框

<div id="customAlert" style="display:none; position:fixed; top:50%; left:50%; transform:translate(-50%,-50%); background:white; padding:20px; border:1px solid #ccc; z-index:1000;">
    <p id="alertMessage"></p>
    <button onclick="hideAlert()">确定</button>
</div>

<script>
function showAlert(message) {
    document.getElementById('alertMessage').textContent = message;
    document.getElementById('customAlert').style.display = 'block';
}
function hideAlert() {
    document.getElementById('customAlert').style.display = 'none';
}
</script>

使用第三方库实现高级提示框

SweetAlert2库提供了美观且功能丰富的提示框。

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
Swal.fire({
    title: '提示',
    text: '这是一个漂亮的提示框',
    icon: 'success',
    confirmButtonText: '确定'
});
</script>

实现Toast提示框

创建短暂显示的轻量级提示。

function showToast(message) {
    const toast = document.createElement('div');
    toast.textContent = message;
    toast.style.position = 'fixed';
    toast.style.bottom = '20px';
    toast.style.right = '20px';
    toast.style.padding = '10px 20px';
    toast.style.background = '#333';
    toast.style.color = 'white';
    toast.style.borderRadius = '5px';
    document.body.appendChild(toast);

    setTimeout(() => {
        document.body.removeChild(toast);
    }, 3000);
}

标签: 提示js
分享给朋友:

相关文章

js如何实现继承

js如何实现继承

原型链继承 通过将子类的原型指向父类的实例实现继承。子类实例能够访问父类原型上的属性和方法。 function Parent() { this.name = 'parent'; } Parent…

js 实现vue

js 实现vue

Vue.js 的基本实现 在 JavaScript 中实现 Vue.js 的核心功能,可以通过数据绑定、响应式系统和虚拟 DOM 来实现。以下是实现 Vue.js 核心功能的简化版本。 数据响应式系…

js实现类

js实现类

JavaScript 实现类的几种方式 JavaScript 是一种基于原型的语言,但在 ES6 之后引入了 class 语法糖,使得实现类更加直观。以下是几种常见的实现方式: 使用构造函数 传统的…

js实现抽奖

js实现抽奖

实现抽奖功能的基本思路 抽奖功能的核心是随机选择奖项并展示结果。可以通过数组存储奖项,利用随机数生成索引,最后通过动画增强用户体验。 准备奖项数据 定义一个数组存储奖项信息,每个奖项可以包含名称、图…

js实现授权

js实现授权

授权流程设计 授权流程通常涉及前端与后端的交互,常见方案包括OAuth2.0、JWT等。以JWT为例的典型流程: 用户提交凭证(如用户名密码)到认证服务 服务端验证通过后生成包含用户信息的JWT令牌…

js实现正交

js实现正交

正交的概念 正交在数学和计算机科学中通常指两个向量垂直或线性无关。在编程中,正交性常被用于设计模块化、低耦合的系统。 向量正交判断 判断两个向量是否正交可以通过点积是否为0来实现: functio…