一、为何使用iframe?
一般用来包含别的页面,例如我们可以在我们自己的网站页面加载别人网站的内容
<body>
<div class='btn' >
<input id='btn' type="button" value='加载第1个html文件'/>
<input type="button" value='加载第2个html文件'/>
</div>
<iframe src='model1.html' class='con' id='frameBox'></iframe>
</body>
二、如何在当前页面调用iframe中的标签和内容?
contentWindow、contentDocument
<script>
var frameBox = document.getElementById('frameBox');
var btn = document.getElementById('btn');
btn.onclick = function(){
var frameTit = frameBox.contentWindow.document.getElementsByTagName('h1');
console.log(frameTit[0].innerHTML);
}
</script>
注意由于JS有执行顺序 ,因此不要写成如下样子:
<script>
var frameBox = document.getElementById('frameBox');
var frameTit = frameBox.contentWindow.document.getElementsByTagName('h1');
console.log(frameTit[0].innerHTML);
</script>
另外,var frameTit = frameBox.contentWindow.document.getElementsByTagName(‘h1’);等价于var frameTit = frameBox.contentDocument.getElementsByTagName(‘h1’);但是,contentDocument不兼容IE6和7
三、如何在iframe中调用当前页面的内容?
window.parent、window.top
window.parent.document.getElementsByTagName(‘div’);
window.top.document.getElementsByTagName(‘div’);
四、检测iframe的内容是否加载完成?
<script>
var newFrame = document.createElement('iframe');
newFrame.src = 'model1.html';
document.body.appendChild(newFrame);
newFrame.onload = function(){
alert('已经加载完成iframe框架');
}
</script>
IE下的iframe的onload事件我们需要使用绑定的方式,不然不能够生效。也就是把onload的书写方式调整为attachEvent的书写方式:
newFrame.attachEvent('onload', function(){
alert('已经加载完成iframe框架');
});
五、防止别人使用自己的网站钓鱼?
为别电泳的iframe文件(自己的网站),添加如下代码:
if (window!=window.top) {
window.top.location.href = window.location.href;
};
另外:
1. iframe可用于解决跨域问题
2. iframe不利于SEO