1. 程式人生 > 實用技巧 >JS之將當前視窗設定為頂級視窗

JS之將當前視窗設定為頂級視窗

相關
  • self:返回對當前視窗的引用。等價於 Window 屬性。
  • top:屬性返回最頂層的先輩視窗。該屬性返回對一個頂級視窗的只讀引用。如果視窗本身就是一個頂級視窗,top 屬性存放對視窗自身的引用。如果視窗是一個框架,那麼 top 屬性引用包含框架的頂層視窗。
  • Location 物件:
    Location 物件包含有關當前 URL 的資訊。
    Location 物件是 Window 物件的一個部分,可通過 window.location 屬性來訪問。
程式碼示例

test.html:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
    </head>
	<body>
		這是test視窗(頂級視窗)<br />
		<iframe src="index.html" width="500px" height="500px"></iframe>
	</body>
</html>

index.html:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<title></title>
	</head>
	<body>
		這是index視窗
		<script>
			function setTop(){
				if (window.top != window.self){
					window.top.location = window.self.location;
				}
			}
		</script>
		<input type="button" 
			value="如果當前視窗不是頂級視窗的話,將當前視窗設定為頂級視窗" 
			onclick="setTop()" />
	</body>
</html>


點選按鈕: