如果页面包含框架,则每个框架都拥有自己的window对象,并且保存在frames集合中,可以通过数字索引(从0开始,从左右到右,从上到下)或者框架名称来访问相对应的window对象。
每个window对象都有一个name属性,其中包含着框架的名称。
inded.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JavaScript</title>
</head> <frameset rows="160,*">
<frame src="frame.html" name = "topFrame">
<frameset cols="50%,*" name = "innerFrameset">
<frame src="anotherFrame.html" name="leftFrame">
<frame src="yetanotherFrame.html" name="rightFrame">
</frameset>
</frameset> </html>
frame.html
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body> <div>
topFrame.html
</div> <script type="text/javascript">
var frameName = "topFrame-frame.html"; </script>
</body>
</html>
anotherFrame.html:
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body> <div>
anotherFrame.html
</div> <script type="text/javascript">
var frameName = "leftFrame-anotherFrame.html";
var topwindow = window.top;
var parentWindow = window.parent;
var frame1 = topwindow.frames[0].frameName;
var frame2 = topwindow.frames["leftFrame"].frameName;
console.log(frame1); // topFrame-frame.html
console.log(frame2); // leftFrame-anotherFrame.html
console.log(window.name); // leftFrame
</script>
</body>
</html>
yetanotherFrame.html
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body> <div>
yetanotherFrame.html
</div> <script type="text/javascript"> var frameName = "rightFrame-yetanotherFrame.html";
</script>
</body>
</html>
window对象的属性(与框架有关的):
top:任何一个 window 对象的 top 属性都指向最高层框架,也就是浏览器窗口。而window对象一般都是特定的框架实例,不一定就是最高窗口。
parent:指向当前框架的直接上层框架。parent有可能等于 top,在没有框架的情况下 window、top、parent 都相等。
self:self 就只指向window。
可以跨框架访问另一个框架页面中window的属性。