JS實現模態框

實現簡單彈出框/遮罩層的效果。 

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>彈出框</title>
	<style>
		*{
			padding: 0;
			margin:0;
		}
		body{
			width: 100%;
			height:100%;
			background: #fff;
		}
		.toggleModal{
			padding: 10px 20px;
			color: white;
			background: #409EFF;
			border:none;
			box-shadow: 2px 3px 20px rgba(0,0,0,0.2);
			position: absolute;
			left: 50%;
			top: 50%;
			transform: translate(-50%,-50%);
		}
		.mask{
			position: absolute;
			top: 0;
			bottom: 0;
			left: 0;
			width: 100%;
			height: 100%;
			background: rgba(0,0,0,0.4);
			z-index: 100;
			display: none;
		}
		.modal{
			position: absolute;
			top: 50%;
			left: 50%;
			width: 400px;
			transform: translate(-50%,-50%);
			border-radius: 5px;
			background: #fff;
			box-shadow: 2px 3px 20px rgba(0,0,0,0.2);
			z-index: 120;
			display: none;
		}
		.modal .modal-header{
			height: 50px;
			border-bottom: 1px solid #f5f5f5;
			padding: 0 15px;
		}
		.modal .modal-header p {
			line-height: 50px;
			display: inline-block;
		}
		.modal .modal-header .title{	
			font-size: 18px;
			color: #333;
		}
		.modal .modal-header .close{
			float: right;
			font-size: 26px;
			margin-top: -2px;
			color: #9C9FA4;
			cursor: default;
		}
		.modal .modal-content{
			min-height: 100px;
		}
		.modal .modal-footer .btn{
			padding: 0 20px;
			height: 36px;
			line-height: 36px;
			color: white;
			background: #409EFF;
			border: none;
		}
		.modal .modal-footer{
			border-top: 1px solid #f5f5f5;
			padding: 15px;
			text-align: right;

		}
		.container::after{
			content:"";
			display: block;
			clear: both;
		}
	</style>
</head>
<body>
	<div class="container">
		<div>
			<button class="toggleModal" id="toggleModal">觸發遮罩層</button>
		</div>
		<div class="modal">
			<div class="modal-header">
				<p class="title">這是彈出層的標題</p>
				<p class="close">×</p>
			</div>
			<div class="modal-content">
				
			</div>
			<div class="modal-footer">
				<button class="close btn">關閉</button>
			</div>
		</div>
		<div class="mask"></div>
	</div>
	<script>
		window.onload = function(){
			// 獲取需要使用到的元素
			var toggleModal = document.getElementById("toggleModal");
			var container = document.getElementsByClassName("container")[0];
			var mask = document.getElementsByClassName("mask")[0];
			var modal = document.getElementsByClassName("modal")[0];
			var closes = document.getElementsByClassName("close");
			toggleModal.onclick = show;
			closes[0].onclick = close;
			closes[1].onclick = close;
			function show(){
				mask.style.display = "block";
				modal.style.display = "block";
			}
			function close(){
				mask.style.display = "none";
				modal.style.display = "none";
			}
		}
	</script>
</body>
</html>

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章