当前位置:首页 > JavaScript

js实现toast

2026-02-01 23:24:08JavaScript

实现Toast的基本方法

使用纯JavaScript实现Toast通知可以通过动态创建DOM元素并添加动画效果来完成。以下是一个简单的实现方式:

function showToast(message, duration = 3000) {
  const toast = document.createElement('div');
  toast.className = 'toast';
  toast.textContent = message;

  document.body.appendChild(toast);

  setTimeout(() => {
    toast.classList.add('show');
  }, 10);

  setTimeout(() => {
    toast.classList.remove('show');
    setTimeout(() => {
      document.body.removeChild(toast);
    }, 300);
  }, duration);
}

添加CSS样式

Toast需要配合CSS样式才能正常显示和动画效果:

.toast {
  position: fixed;
  bottom: 20px;
  left: 50%;
  transform: translateX(-50%);
  background-color: rgba(0, 0, 0, 0.7);
  color: white;
  padding: 12px 24px;
  border-radius: 4px;
  opacity: 0;
  transition: opacity 0.3s ease;
  z-index: 9999;
}

.toast.show {
  opacity: 1;
}

使用示例

调用showToast函数即可显示通知:

showToast('操作成功', 2000);

高级实现选项

可以扩展基础功能实现更多特性:

function showToast(options) {
  const defaults = {
    message: '',
    duration: 3000,
    position: 'bottom',
    type: 'default'
  };

  const config = {...defaults, ...options};
  const toast = document.createElement('div');

  toast.className = `toast toast-${config.position} toast-${config.type}`;
  toast.textContent = config.message;

  document.body.appendChild(toast);

  setTimeout(() => toast.classList.add('show'), 10);
  setTimeout(() => {
    toast.classList.remove('show');
    setTimeout(() => document.body.removeChild(toast), 300);
  }, config.duration);
}

对应的扩展CSS

.toast-top {
  top: 20px;
  bottom: auto;
}

.toast-center {
  top: 50%;
  bottom: auto;
  transform: translate(-50%, -50%);
}

.toast-success {
  background-color: #4CAF50;
}

.toast-error {
  background-color: #F44336;
}

.toast-warning {
  background-color: #FF9800;
}

使用第三方库

如果需要更复杂的功能,可以考虑使用现成的Toast库:

js实现toast

标签: jstoast
分享给朋友:

相关文章

js实现vue

js实现vue

Vue.js 简介 Vue.js 是一个渐进式 JavaScript 框架,用于构建用户界面。其核心库专注于视图层,易于与其他库或现有项目整合。 实现 Vue.js 的基本步骤 安装 Vue.…

js实现轮播

js实现轮播

实现轮播图的基本思路 轮播图的核心逻辑是通过定时切换展示的图片或内容,通常结合左右滑动按钮和指示器(小圆点)增强交互性。以下是基于原生JavaScript的实现方法。 HTML结构 构建轮播图的HT…

js实现轮播图

js实现轮播图

基础轮播图实现 使用HTML、CSS和JavaScript实现一个简单的自动轮播图。HTML结构包含一个容器和多个图片项。 <div class="slider"> <div…

js实现打印

js实现打印

使用window.print()方法实现打印 在JavaScript中,可以通过调用window.print()方法直接触发浏览器的打印功能。这会打开系统的打印对话框,用户可以选择打印机和设置打印选项…

js实现文件下载

js实现文件下载

使用 a 标签下载文件 通过动态创建 a 标签并设置 download 属性实现文件下载。适用于已知文件 URL 或 Blob 数据的情况。 function downloadFile(url,…

js实现选项卡

js实现选项卡

实现选项卡的基本思路 选项卡通常由一组标签和对应的内容面板组成。点击标签时,显示对应的内容面板,隐藏其他面板。实现这一效果需要结合HTML结构、CSS样式和JavaScript交互逻辑。 HTML…