Toast(吐司)是一种轻量级的通知提示框,通常用于显示简短的消息或状态更新。它会在屏幕上短暂显示,然后自动消失。在JavaScript中,可以通过设置定时器来控制Toast的显示时间。
以下是一个简单的JavaScript示例,展示如何设置Toast的显示时间:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Toast Example</title>
<style>
#toast {
visibility: hidden;
min-width: 250px;
margin-left: -125px;
background-color: #333;
color: #fff;
text-align: center;
border-radius: 2px;
padding: 16px;
position: fixed;
z-index: 1;
left: 50%;
bottom: 30px;
font-size: 17px;
}
</style>
</head>
<body>
<div id="toast">This is a toast message!</div>
<button onclick="showToast()">Show Toast</button>
<script>
function showToast() {
var toast = document.getElementById("toast");
toast.style.visibility = "visible";
setTimeout(function(){
toast.style.visibility = "hidden";
}, 3000); // 设置显示时间为3秒
}
</script>
</body>
</html>
原因:
解决方法:
requestAnimationFrame
来优化动画效果,提高定时器的准确性。function showToast() {
var toast = document.getElementById("toast");
toast.style.visibility = "visible";
var startTime = Date.now();
var duration = 3000; // 3秒
function checkTime() {
if (Date.now() - startTime >= duration) {
toast.style.visibility = "hidden";
} else {
requestAnimationFrame(checkTime);
}
}
requestAnimationFrame(checkTime);
}
通过这种方式,可以更精确地控制Toast的显示时间,避免因浏览器性能问题导致的延迟。
领取专属 10元无门槛券
手把手带您无忧上云