javascript学习-iframe

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']
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值