现在很多UI框架都有好看且美观的消息气泡。但有时简单写个东西,只需要一个气泡,不想引入框架中太多的东西,所以就需要手写一个消息气泡。
本文将展示使用原生JavaScript实现一个简单的自定义消息气泡,没有太多文字,主要看代码及注释即可。
前排提示:老狗前端技术有限,气泡不够美观,会前端的大佬可以自行优化!
提示:可以自己新建个html文件,将下方代码复制填写到该文件中,浏览器打开该文件即可查看代码效果。
html<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>message-babo</title>
    <style type="text/css">
      #msg-container {
        position: fixed;
        top: 5%;
        left: 46%;
        text-align: center;
        display: none;
      }
      /* 成功气泡css */
      .success-msg {
        margin: 5px;
        padding: 5px 10px;
        border-radius: 3px;
        border: 1px solid #2e7b20;
        background-color: #80d970;
        color: #2e7b20;
        font-size: 16px;
      }
      
      /* 失败气泡css */
      .error-msg {
        margin: 5px;
        padding: 5px 10px;
        border-radius: 3px;
        border: 1px solid #e51717;
        background-color: #ffb9b9;
        color: #e51717;
        font-size: 16px;
      }
      
      .buttons{
        padding: 1rem;
      }
    </style>
    
    <script>
      // 显示成功气泡的方法
      function alertSuccess(msg, duration) {
        alertCust(msg, "success-msg", duration);
      }
      
      // 显示失败气泡的方法
      function alertError(msg, duration) {
        alertCust(msg, "error-msg", duration);
      }
      
      /**
       * 显示气泡的方法
       * 
       * @param msg        气泡显示内容
       * @param className  自定义元素的类名
       * @param duration   气泡消失时间-毫秒
       */
      function alertCust(msg, className, duration) {
        // console.log(msg, className);
        // 获取气泡容器
        const msgContainer = document.getElementById("msg-container");
        // 创建一个div
        let msgDiv = document.createElement("div");
        // 给新建div赋予气泡属性及信息
        msgDiv.innerText = msg;
        msgDiv.className = className;
        // 将气泡添加到气泡容器
        msgContainer.appendChild(msgDiv);
        msgContainer.style.display = "block";
        
        // 设置一个定时任务,用于让气泡消失
        window.setTimeout(function () {
          // 删除上面新建的气泡
          msgContainer.removeChild(msgDiv);
          // 如果气泡容器内部没有内容了,则将气泡容器隐藏
          if (msgContainer.innerHTML == null || msgContainer.innerHTML.length === 0){
            msgContainer.style.display = "none";
          }
        }, duration)
      }
    </script>
  </head>
  <body>
    <div style="text-align: center">
      <!-- 点击显示成功气泡 -->
      <button onclick="alertSuccess('成功', 3000)" class="buttons">show-success</button>
      <!-- 点击显示失败气泡 -->
      <button onclick="alertError('失败', 10000)" class="buttons">show-error</button>
    <div>
    <!-- 消息气泡容器 -->
    <div id="msg-container"></div>
  </body>
</html>
如果你觉得本文对你有用,想要给作者一些赞助,可以动动小手点击下方广告给予支持,万分感谢~
您的每次点击都能给予作者更多分享的动力!请无情点击吧:
本文作者:DingDangDog
本文链接:
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!