HTMl 原生实现简单的toast 消息提示
一,需求分析
1,装toast组件容器需要为一个从上往下进行布局的内容
2,toast组件添加后需要播放消失动画
消失动画的表现方式
1,布局往上推,然后缓慢变透明直至消失
2,消失过程中,后加入的toast位置随着逐渐消失的toast的位置改变而跟着改变
二,代码实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 | <! DOCTYPE html> < html lang="en"> < head > < meta charset="UTF-8"> < meta http-equiv="X-UA-Compatible" content="IE=edge"> < meta name="viewport" content="width=device-width, initial-scale=1.0"> < title >简易Toast实现</ title > < style > .toast-layout{ position: fixed; width: 100vw; height: 100vh; text-align: center; } .toast .content{ margin: auto; margin-bottom: 16px; width: max-content; padding: 20px; text-align: center; color: white; background-color: black; border-radius: 28px; } .hide-toast{ animation:remove .5s ease-out; } @keyframes remove { from{ height: 56px; opacity: 1; } to{ height: 0; opacity: 0; } } </ style > </ head > < body > < script > function showToast(content, duration) { var toast = document.getElementById("Toast") if (toast == null) { var toast = document.createElement("div") toast.setAttribute("id", "Toast") toast.setAttribute("class", "toast-layout") document.body.appendChild(toast) showToast(content, duration) return } var toastItem = document.createElement("div") toastItem.setAttribute("class", "toast") toastItem.innerHTML = '< div class="content">' + content + '</ div >' setTimeout(function () { toastItem.setAttribute('class', 'toast hide-toast') }, duration) toastItem.onanimationend = function () { toastItem.remove() } toast.appendChild(toastItem) } </ script > < button onclick="showToast('你好啊你好啊', 1200)">测试</ button > </ body > </ html > |
三,演示
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库