You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

自定义CSS Toastr通知div随机显示求助(含codeseven Toastr方案)

嘿,我来帮你搞定这个随机显示Toastr通知的问题,分两种方案给你,你看哪种更适合你的场景:

方案一:自定义Div实现随机显示

首先,先把你的HTML结构统一一下,给所有通知div加个共同的class,比如toastr-notification,像这样:

<div class="toastr-notification" id="toastr1">这是第一条自定义通知</div>
<div class="toastr-notification" id="toastr2">这是第二条自定义通知</div>
<div class="toastr-notification" id="toastr3">这是第三条自定义通知</div>

然后在CSS里先默认把所有通知藏起来,再加上你的自定义样式:

.toastr-notification {
  display: none; /* 关键:默认隐藏所有 */
  /* 下面是你的自定义样式,比如定位、背景这些 */
  position: fixed;
  top: 20px;
  right: 20px;
  padding: 15px 20px;
  background-color: #333;
  color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.2);
}

接下来用JS在页面加载时随机挑一个显示,其他保持隐藏:

// 等页面DOM加载完成再执行
document.addEventListener('DOMContentLoaded', function() {
  // 拿到所有通知div
  const allNotifications = document.querySelectorAll('.toastr-notification');
  // 如果没有通知就直接返回,避免报错
  if (allNotifications.length === 0) return;

  // 生成一个0到通知数量-1的随机整数索引
  const randomIdx = Math.floor(Math.random() * allNotifications.length);

  // 遍历所有通知,只显示随机选中的那个
  allNotifications.forEach((item, idx) => {
    if (idx === randomIdx) {
      item.style.display = 'block'; // 或者你用flex之类的显示方式,看你CSS布局
    } else {
      item.style.display = 'none';
    }
  });
});

你之前可能踩的坑:要么没默认隐藏所有通知,要么随机数没取整(比如直接用Math.random()得到的是0-1的小数,没法当索引),用Math.floor()处理后就能精准选中单个div了。

方案二:用codeseven Toastr官方库实现

如果不想自己折腾div的显示隐藏,直接用官方库更省心,步骤如下:
首先确保你已经引入了Toastr的CSS和JS文件(本地导入就行,不用外链):

<link rel="stylesheet" href="path/to/toastr.css">
<script src="path/to/toastr.js"></script>

然后写JS代码定义一批通知内容,随机选一个调用Toastr显示:

document.addEventListener('DOMContentLoaded', function() {
  // 把所有要显示的通知内容存成数组
  const toastContentList = [
    { title: '温馨提示', message: '今天也要好好干活哦~' },
    { title: '系统通知', message: '您的账号已安全登录' },
    { title: '小提醒', message: '记得保存当前进度' }
  ];

  // 随机选一条
  const randomToast = toastContentList[Math.floor(Math.random() * toastContentList.length)];

  // 调用Toastr显示,还可以换成success/warning/error类型
  toastr.info(randomToast.message, randomToast.title);
});

这种方式Toastr会自动帮你创建、管理通知DOM,不用自己操心显示隐藏的逻辑,非常方便。

小提醒
  • 如果之前出现所有div同时显示:检查CSS里有没有默认加display: none,这是关键前提。
  • 如果完全没效果:看看JS是不是在DOM加载完成前就执行了(比如放在<head>里没加DOMContentLoaded事件),或者选择器写错了(比如把class写成id了)。

内容的提问来源于stack exchange,提问作者Dzo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 09:43:06