本篇文章介绍了 js 操作 iframe 的一些方法的实例代码与步骤,有需要的朋友可以参考一下
Javascript 是一种由 Netscape 的 LiveScript 发展而来的原型化继承的基于对象的动态类型的区分大小写的客户端脚本语言,主要目的是为了解决服务器端语言,比如 Perl,遗留的速度问题,为客户提供更流畅的浏览效果。
1. 获得 iframe 的 window 对象
存在跨域访问限制。
chrome:iframeElement. contentWindow
firefox: iframeElement.contentWindow
ie6:iframeElement.contentWindow
文章 Iframes, onload, and document.domain 中说 "he iframe element object has a property called contentDocument that contains the iframe's document object, so you can use the parentWindow property to retrieve the window object." 意思就是一些浏览器可以通过 iframeElement.contentDocument.parentWindow 获得 iframe 的 window 对象。但经过测试 firefox、chrome 的 element.contentDocument 对象没有 parentWindow 属性。
(javascript)
- function getIframeWindow(element){
- return element.contentWindow;
- //return element.contentWindow || element.contentDocument.parentWindow;
- }
2. 获得 iframe 的 document 对象
存在跨域访问限制。
chrome:iframeElement.contentDocument
firefox:iframeElement.contentDocument
ie:element.contentWindow.document
备注:ie 没有 iframeElement.contentDocument 属性。
(javascript)
- var getIframeDocument = function(element) {
- return element.contentDocument || element.contentWindow.document;
- };
3. iframe 中获得父页面的 window 对象
存在跨域访问限制。
父页面:window.parent
顶层页面:window.top
适用于所有浏览器
window.frameElement(类型:htmlElement),适用于所有浏览器
5. iframe 的 onload 事件
非 ie 浏览器都提供了 onload 事件。例如下面代码在 ie 中是不会有弹出框的。
(javascript)
- var ifr = document.createElement('iframe');
- ifr.src = 'http://www.phperz.com/index.php';
- ifr.onload = function() {
- alert('loaded');
- };
- document.body.appendChild(ifr);
但是 ie 却又似乎提供了 onload 事件,下面两种方法都会触发 onload
方法一:
- <iframe onload="alert('loaded');" src="http://www.phperz.com/index.php">
- </iframe>
// 只有 ie 才支持为 createElement 传递这样的参数 由于 iframe 元素包含于父级页面中,因此以上方法均不存在跨域问题。
来源: