以下是一个简单的纯JS写的toast提示框,包括了基本的显示和隐藏功能:

<!DOCTYPE html>
<html>
<head>
	<title>Toast提示框</title>
	<style>
		.toast {
			position: fixed;
			top: 50%;
			left: 50%;
			transform: translate(-50%, -50%);
			background-color: black;
			color: white;
			padding: 10px;
			border-radius: 5px;
			opacity: 0;
			transition: opacity 0.5s ease-in-out;
			z-index: 9999;
		}
	</style>
</head>
<body>
	<button onclick="showToast()">显示Toast提示框</button>

	<script>
		function showToast() {
			var toast = document.createElement('div');
			toast.classList.add('toast');
			toast.innerHTML = '这是一条Toast提示信息';
			document.body.appendChild(toast);
			setTimeout(function() {
				toast.style.opacity = 1;
			}, 100);
			setTimeout(function() {
				toast.style.opacity = 0;
			}, 2000);
			setTimeout(function() {
				document.body.removeChild(toast);
			}, 2500);
		}
	</script>
</body>
</html>

该toast提示框会在点击按钮后出现,然后在2秒后自动消失。可以根据需要修改显示和消失的时间。同时,为了使该提示框居中显示,将其定位为fixed,并设置top和left为50%,再通过transform属性将其向左和向上平移50%的宽度和高度。另外,为了使该提示框在最上方显示,将其z-index属性设置为9999。

纯js 写一个 toast 提示框

原文地址: https://www.cveoy.top/t/topic/bgfh 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录