使用 Tailwind CSS 显示 Toast 消息
下面的完整示例向您展示了如何创建 toast,这是一种模仿移动应用程序上流行的推送通知的警报消息。通常包含一条简短的消息,并在出现几秒钟后自动消失。我们通过使用 Tailwind CSS 和一点原始的 Javascript(只是这种编程语言的几行代码)来实现它。
预习
我们的示例网页有一个按钮。单击此按钮时,右下角将显示一个 toast。它会在那里停留 5 秒钟,然后自动消失。
编码
完整的代码和注释中的解释:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script src="https://cdn.tailwindcss.com"></script>
<title>KindaCode.com</title>
</head>
<body class="bg-amber-100 px-20 py-10">
<h3 class="mt-4 text-3xl">Toast Example</h3>
<!-- This button is used to call the showToast() function -->
<div class="mt-10 space-x-5">
<button onclick="showToast()" class="px-6 py-3 bg-blue-500 hover:bg-blue-600 text-white">Show Toast</button>
</div>
<!-- Implement the toast -->
<div id="myToast" class="hidden fixed right-10 bottom-10 px-5 py-4 border-r-8 border-blue-500 bg-white drop-shadow-lg">
<p class="text-sm">
<!-- Polish the toast with an circle blue "i" (stands for information) -->
<span class="mr-2 inline-block px-3 py-1 rounded-full bg-blue-500 text-white font-extrabold">i</span>
This is a toast. Welcome to KindaCode.com
</p>
</div>
<!-- Javascript code -->
<script>
function showToast() {
// Show the toast
document.getElementById("myToast").classList.remove("hidden");
// Hide the toast after 5 seconds (5000ms)
// you can set a shorter/longer time by replacing "5000" with another number
setTimeout(function () {
document.getElementById("myToast").classList.add("hidden");
}, 5000);
}
</script>
</body>
</html>
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。