iframe
iframe的一些基本属性:
- src iframe页面地址,有同域跨域之分
- height iframe高度
- width iframe宽度
- name iframe命名,可通过window.frames[xxx]被调用
- scrolling iframe滚动模式
- sandbox html5新特性,用于限制iframe的功能
格式:
<iframe src="demo.html" height="300" width="500" name="demo" scrolling="auto" sandbox="allow-same-origin"></iframe>
例子:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<style type="text/css">
body{
display: flex;
height: 100vh;
}
.left{
width: 200px;
height: 100%;
background: skyblue;
}
.right{
flex: 1;
background: oldlace;
}
.right iframe{
width: 100%;
height: 100%;
}
</style>
</head>
<body>
<div class="left">
<h1>导航列表</h1>
<h3><button >国内新闻news1</button></h3>
<h3><button>国外新闻news2</button></h3>
<h3><button>娱乐新闻news3</button></h3>
<h3><button>体育新闻news4</button></h3>
<h2><button class="linkto" data-src="http://baidu.com">百度一下</button></h2>
</div>
<div class="right">
<iframe src="news1.html"></iframe>
</div>
<script type="text/javascript">
var btns=document.querySelectorAll("h3 button")
var iframe=document.querySelector("iframe");
btns.forEach(function(item,index){
item.onclick=function(){
iframe.setAttribute("src","news"+(index+1)+".html");
}
})
var linkto=document.querySelector(".linkto");
linkto.onclick=function(event){
var url=this.getAttribute("data-src");
//var url=event.target.dataset.src;
iframe.setAttribute("src",url);
}
</script>
</body>
</html>
结果:
我们可以通过contentWindow和contentDocument两个API获取iframe的window对象和document对象。
var iwindow = iframe.contentWindow; // 获取iframe的window对象
var idoc = iframe.contentDocument; // 获取iframe的document对象,但是要在同源(同协议同ip同域名同端口)的情况下才能获取
可以通过window.frames[iframeName]来调用iframe。
iframe = window.frames['demo']