如何在网页弹出一个Toast
前言:
在如今H5与原生交互越来越多的情况下,大部分情况下,吐司的功能都可以由客户端原生来实现,但是在有些特殊的情况下会需要页面来弹出一个吐司,这篇博客记录如何通过html css js实现一个Web版的吐司
效果图。
1,html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1,maximum-scale=1,user-scalable=no">
<title>Toast Demo</title>
</head>
<link href="toast.css" rel="stylesheet" />
<style>
body{
text-align: center;
margin-top: 100px;
}
input{
width: 100px;
height: 40px;
background: #333333;
border: none;
color: white;
outline:none
}
input:enabled:active{
background: gainsboro;
border: none;
outline:none;
color: white;
}
</style>
<body>
<input type="button" value="show Toast" onclick="showToast()"/>
</body>
<script src="Toast.js"></script>
<script>
function showToast() {
Toast.toast("Hello");
}
</script>
</html>
css
.toast-container {
position: fixed;
z-index: 9999;
bottom: 50px;
width: 100%;
-webkit-transition: opacity .8s;
transition: opacity .8s;
opacity: 0
}
.toast-container.toast-active {
opacity: 1
}
.toast-message-container {
font-size: 14px;
width: 170px;
margin: 5px auto;
padding: 5px;
text-align: center;
color: #333;
border-radius: 7px;
background-color: #d8d8d8
}
js
var Toast = {};
Toast.toast = function(msg) {
var active = "toast-active";
var div = document.createElement("div");
div.classList.add("toast-container")
div.innerHTML = '<div class="toast-message-container">' + msg + "</div>"
div.addEventListener("webkitTransitionEnd", function() {
div.classList.contains(active) || div.parentNode.removeChild(div)
});
document.body.appendChild(div)
div.offsetHeight
div.classList.add(active)
setTimeout(function() {
div.classList.remove(active)
}, 1500)
}