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

如何无需点击触发自定义对话框(非JavaScript Alert)

自定义自动触发对话框的修复方案

原代码存在的问题:

  • CSS代码未包裹在<style>标签内,浏览器无法识别解析
  • JavaScript仅拼接了对话框内部HTML字符串,但未将其插入DOM树,导致页面无显示
  • 缺少带.BoxAlert类的外层容器,无法应用预设的弹窗样式

修复后的完整代码:

<!DOCTYPE html>
<html>
<head>
  <style>
    .BoxAlert {
      position: absolute;
      z-index: 10;
      left: 10%;
      background-color: #8695b7;
      color: #090908;
      height: 150px;
      width: 320px;
      font-size: 20px;
      display: flex;
      align-items: center;
      justify-content: center;
    }

    .BoxAlert:before {
      content: "";
      position: fixed;
      z-index: -10;
      display: block;
      top: 0;
      left: 0;
      bottom: 0;
      right: 0;
      background: #0007;
    }

    .BoxAlert > div {
      border: 0.25em solid black;
      border-radius: 0.25em;
      padding: 0.25em;
      background: #fff;
      width: 90%;
    }
  </style>
</head>
<body>
  <script>
    function openBoxAlert() {
      // 创建外层弹窗容器
      const alertContainer = document.createElement('div');
      alertContainer.className = 'BoxAlert';
      
      // 拼接弹窗内容
      let m = "<div style='text-align: center;'>Vous êtes <br>";
      m += "Pour trouver le point Relais";
      m += "<br><span style='color: red; font-weight: bold;'>quelques secondes</span>";
      m += "<br></div>";
      
      // 将内容插入容器,再添加到body中
      alertContainer.innerHTML = m;
      document.body.appendChild(alertContainer);
    }
    // 页面加载时自动触发
    openBoxAlert();
  </script>
</body>
</html>

说明:

  • 给CSS添加了<style>标签,确保样式正常生效
  • 创建带.BoxAlert类的容器元素,将拼接的内容插入后添加到页面body中
  • 新增display: flex等样式,让弹窗内容居中显示,优化视觉效果

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 19:16:04