一,需求分析
1,装toast组件容器需要为一个从上往下进行布局的内容
2,toast组件添加后需要播放消失动画
消失动画的表现方式
1,布局往上推,然后缓慢变透明直至消失
2,消失过程中,后加入的toast位置随着逐渐消失的toast的位置改变而跟着改变
二,代码实现
<!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; 100vw; height: 100vh; text-align: center; } .toast .content{ margin: auto; margin-bottom: 16px; 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>
三,演示