页面控制iframe元素
iframe元素.contentWindow.document.getElementById(''); //iframe元素.contentWindow为iframe对象
iframe元素.contentDocument.getElementById(''); //iframe元素.contentDocument为document对象,IE6和IE7不支持
iframe元素控制父元素
window.parent.document.getElementById(''); //window.parent为iframe的父元素
iframe元素控制顶层元素
window.top.document.getElementById(''); //window.top为iframe的顶层元素
iframe.onload 元素
iframe元素.onload
iframe元素.attachEvent('onload',function(){}) //用在IE上
举例:
1、阻止网站被钓鱼
<!--主页面--> <iframe src = 'iframe1.html'></iframe> <!--iframe1.html页面--> <p>iframe1的页面</p>
<!--在iframe的页面写JS--> if (window!=window.top) { window.top.location.href = window.location.href ; } //当window(iframe的页面) 不等于 window.top(主页面) 时 //window.location.href 是iframe的网址 //window.top.location.href 是主页面的网址
2、改变iframe的大小
思路:
1) 一个主页面,两个iframe页面,由btn来切换iframe中的src,根据iframe页面的大小来改变iframe元素。
2) iframe元素的src改变
3) 页面控制iframe元素: iframe元素.style.height = iframe元素.contentWindow.document.body.offsetHeight + 'px';
4) 在进行大小切换的时候,需要使用setTimeout来延迟一下,否则会无效,即:
setTimeout(function(){
iframe元素.style.height = iframe元素.contentWindow.document.body.offsetHeight + 'px';
},100);
jquery:
DOM方法:
父窗口操作IFRAME:window.frames["iframeSon"].document
IFRAME操作父窗口: window.parent.document
jquery方法:
在父窗口中操作 选中IFRAME中的所有输入框: $(window.frames["iframeSon"].document).find(”:text”);
在IFRAME中操作 选中父窗口中的所有输入框:$(window.parent.document).find(”:text”)
$(window.parent.document.body).find()
跨域:
方法一:(IE不支持,而且只能传一次值)
1、创建一个iframe,设置src为空
2、在将iframe.contentWindow.name的值设置成string
3、重定向iframe的src为真实的值
4、在iframe.html页面,就可获取window.name的值了。
方法二:(IE8、IE7、IE6不支持)
1、iframe的src为真实的值
2、iframe.onload的时候进行
3、iframe.contentWindow.postMessage(string,'http://www.baidu.com'),第一个参数要设置的值(字符串类型),第二个参数为网址。
4、在iframe.html页面去获取值,如下:
window.addEventListener('message',function(event){
console.log(event.data);
},false);