自己手动写一个js 的toast提示框

闲来无聊,就尝试着自己写一个toast,因为之前写网页是一直会用到的,所以就自己造了个轮子,也当作学习记录(有不好的地方请多多指教),下面贴代码

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<meta name='viewport' content='width=device-width,minimum-scale=1.0 maximum-scale=1.0 user-scalable=no' /> 
	<title>demo</title>
	<style>
		*{
			padding: 0;
			margin: 0;
		}
		.yg-toast{
			position: fixed;
			background: rgba(0,0,0,.7);
			border-radius: 4px;
			top: 90%;
			left: 50%;
			transform: translate(-50%,-50%);
			max-width: 60%;
			text-align: center;
			transition: all .1s;
		}
		.yg-toast-text{
			color: #fff;
			padding: 4px 10px;
		    padding-bottom: 6px;
		}
	</style>
</head>
<body>
</body>
<script type="text/javascript">
	//立即执行函数
	(function(window , undefined ){ 
		var Ygtoast = function(){ //构造函数大驼峰命名法
		};
		Ygtoast.prototype={  //prototype 属性使您有能力向对象添加属性和方法。
			create: function(str,duration) {
				let self = this;
				var toastHtml = '';
				var toastText = '<div class="yg-toast-text">'+str+'</div>';
				toastHtml = '<div class="yg-toast">'+toastText+'</div>';
				if(document.querySelector(".yg-toast"))return;    //当还没hide时禁止重复点击
				document.body.insertAdjacentHTML('beforeend', toastHtml);
				duration == null ? duration=2000 : '';  //如果toast没有加上时间,默认2000毫秒;
	            self.show();
	            setTimeout(function(){
                    self.hide();
                }, duration);
			},
			show:function(){
				let self = this;
	            document.querySelector(".yg-toast").style.display = "block";
	            document.querySelector(".yg-toast").style.marginTop =  "-"+Math.round(document.querySelector(".yg-toast").offsetHeight/2)+"px";
	            if(document.querySelector(".yg-toast"))return;
			},
			hide:function(){
				var self = this;
	            if(document.querySelector(".yg-toast")){
	                document.querySelector(".yg-toast").parentNode.removeChild(document.querySelector(".yg-toast"));
	            }
			},
			toast:function(str,duration){
				var self = this;
				return self.create(str,duration);
			}
		};
		window.Ygtoast = Ygtoast;
	}(window));

	// 以上是造轮子

	// 调用
	var yg = new Ygtoast();
	yg.toast("你说神马",1500);
</script>
</html>

代码可以直接复制使用

  • 6
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值