OBJUI

JavaScript实现自定义信息弹窗

2024-06-21 16:59:57 450

弹窗功能,是每个后台管理系统和有交互的前端页面,必不可少的的功能。市面上这个功能有很多,但大部分都是一整体框架的,比较臃肿。所以就用原生JS自己写一个。


function message(message, type='info') {  
  // Toast容器的默认样式,参考Bootstrap Alert样式  
  const toastStyle = {  
    position: 'fixed',  
    top: '0', // 初始位置在屏幕顶部之上  
    left: '50%',  
    transform: 'translateX(-50%)',  
    zIndex: 9999,  
    padding: '3px 5px',  
    borderRadius: '4px',  
    boxShadow: '0 0.25rem 0.75rem rgba(0, 0, 0, 0.1)',  
    display: 'block',  
    opacity: '0',  
    transition: 'opacity 0.15s linear, transform 0.15s ease-in-out',  
    backgroundColor: '#fff',  
    border: '1px solid transparent',  
    maxWidth: '350px'  
  };  
  
  // 根据类型设置不同的背景色和边框色  
  const toastTypes = {  
    success: { backgroundColor: '#d4edda', borderColor: '#c3e6cb', textColor: '#155724' },  
    error: { backgroundColor: '#f8d7da', borderColor: '#f5c6cb', textColor: '#721c24' },  
    info: { backgroundColor: '#d1ecf1', borderColor: '#bee5eb', textColor: '#0c5460' },  
    warning: { backgroundColor: '#fff3cd', borderColor: '#ffeeba', textColor: '#856404' }  
  };  
  
  // 创建Toast容器元素  
  const toastContainer = document.createElement('div');  
  toastContainer.className = 'toast'; // 添加一个通用的类名以便CSS样式应用  
  Object.keys(toastStyle).forEach(key => {  
    toastContainer.style[key] = toastStyle[key];  
  });

  if (toastTypes[type]) {  
    Object.keys(toastTypes[type]).forEach(key => {  
      if (key === 'backgroundColor' || key === 'borderColor' || key === 'textColor') {  
        // 对于背景色、边框色和文本色,我们直接应用它们  
        toastContainer.style[key] = toastTypes[type][key];  
      } else if (key === 'zIndex') {  
        // 注意:在toastTypes中通常不包含zIndex,但这里只是为了演示  
        toastContainer.style.zIndex = toastTypes[type][key];  
      }  
    });  
  }  
  
  // 创建Toast内容元素  
  const toastContent = document.createElement('div');  
  toastContent.className = 'toast-body'; // 添加内容区域的类名  
  toastContent.style.color = toastTypes[type] ? toastTypes[type].textColor : 'inherit'; // 设置文本颜色  
  toastContent.textContent = message;  
  
  // 将内容添加到Toast容器中  
  toastContainer.appendChild(toastContent);  
  
  // 获取Toast容器元素(可能之前已经存在)  
  const existingToast = document.querySelector('.toast');  
  if (existingToast) {  
    existingToast.remove(); // 如果存在,先移除  
  }  
  
  // 将Toast容器添加到body中  
  document.body.appendChild(toastContainer);  
  
  // 显示Toast(从上往下淡入)  
  toastContainer.style.opacity = '1';  
  toastContainer.style.transform = 'translateY(20px)';  
  
  // 设置Toast的自动隐藏(淡出后移除)  
  setTimeout(function() {  
    toastContainer.style.opacity = '0';  
    toastContainer.style.transform = 'translateY(-50px)';  
    setTimeout(function() {  
      toastContainer.remove(); // 当淡出和移出完成后,从DOM中移除Toast  
    }, 300); // 淡出动画时长  
  }, 3000); // Toast显示3秒后自动隐藏  
}  


//使用示例
message('操作成功','success');
message('操作失败','error');



更多精彩,请关注公众号

微信公众号

评论:
热门文章: