1. 程式人生 > >DIV+IFrame實現頁面彈出視窗

DIV+IFrame實現頁面彈出視窗

需求:頁面點選超連結或者按鈕的時候彈出子視窗,子視窗中編寫資料提交給父視窗,父子視窗頁面不重新整理。

思路:

父視窗:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<input type="text" id="message" disabled="disabled">
	<br>
	<a href="javascript:show();"> <font>彈出框</font>
	</a>
	<div id="myDiv" onclick="cancle(this);"
		style="position: absolute; width: 100%; height: 100%; background-color: rgba(0, 0, 0, 0.2); z-index: 998">
		<div id="popupDiv" 
			style="position: absolute; width: 80%; height: 80%; background-color: white; position: absolute; left: 50%; top: 50%; margin-left: -40%; margin-top: -20%;">
			<iframe id="myFrame" frameborder="0" src="show.html"
				style="position: absolute; width: 100%; height: 100%; border-radius: 3px;"></iframe>
		</div>
	</div>
</body>
<script type="text/javascript">
	var myDiv = document.getElementById("myDiv");
	function myfun() {
		// 隱藏myDiv
		myDiv.style.display = "none";
	}
	function cancle(obj) {
		obj.style.display = "none";
	}
	function show() {
		myDiv.style.display = "block";
	}
	function get(data) {
		var message = document.getElementById("message");
		message.value = data;
		myDiv.style.display = "none";
	}
	window.onload = myfun;
</script>
</html>
子視窗:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<div id="allDiv">
		<input type="text" id="data" value="預設值"> <input type="button"
			id="send" onclick="send();" value="傳值給父視窗">
		<h1>彈出框</h1>
		<h1>彈出框</h1>
		<h1>彈出框</h1>
		<h1>彈出框</h1>
		<h1>彈出框</h1>
		<h1>彈出框</h1>
		<h1>彈出框</h1>
		<h1>彈出框</h1>
		<h1>彈出框</h1>
		<h1>彈出框</h1>
		<h1>彈出框</h1>
		<h1>彈出框</h1>
		<h1>彈出框</h1>
		<h1>彈出框</h1>
		<h1>彈出框</h1>
		<h1>彈出框</h1>
		<h1>彈出框</h1>
		<h1>彈出框</h1>
		<h1>彈出框</h1>
		<h1>彈出框</h1>
		<h1>彈出框</h1>
		<h1>彈出框</h1>
		<h1>彈出框</h1>
		<h1>彈出框</h1>
		<h1>彈出框</h1>
		<h1>彈出框</h1>
	</div>
</body>
<script type="text/javascript">
	function load() {
		// 設定滾動條 
		var allDiv = document.getElementById("allDiv");
		allDiv.style.overflow = "auto";
	}
	function send() {
		var data = document.getElementById("data").value;
		window.parent.get(data);
	}
	window.onload = load;
</script>
</html>

效果圖:

點選外面的區域也可以隱藏。