iframe简直接受页面的福音

362 阅读1分钟

iframe

监听页面上iframe

如果页面上有iframe时,鼠标点击在iframe内时,包含iframe的document是不响应任何事件的,

例如:

$("#iframe1").click(function(){//点击iframe
            alert("点击1");
 });

或者   

 $(function(){//给iframe循环绑定click事件
            for(var n=1;n<=7;n++){
                $("#iframe"+n).bind("click",{n:n}, clickHandler);
            }
            function clickHandler(event) {
                var n = event.data.n;
                alert("点击"+n);
            }
 });

均行不通。

所以需要给iframe绑定类似的事件,当iframe指向的是第三方的内容时,还要考虑跨域的问题,因此通过操作iframe的document是行不通的,还好有document.activeElement可供我们使用,最终的解决方案如下:

如何监控iframe里面页面的点击事件

根据浏览器同源策略,如果iframe中是一个跨域的页面,那么在父页面中无法监听到iframe页面中的所有行为。


$('iframe').hover(
function () {
  alert('AD frame!'); 
);

js/jquery中刷新iframe方法(兼容主流)

js实现刷新两种方式:


1.  `//方法1`
1.  `document.getElementById('FrameID').contentWindow.location.reload(true);`
1.  `//方法2`
1.  `document.getElementById('youriframe').src=src;`

`实例:`


jquery实现强制刷新


1.  $('#iframe').attr('src', $('#iframe').attr('src'));

js获取iframe中的元素以及在iframe中获取父级的元素(包括iframe中不存在name和id的情况)

第一种情况:iframe中不存在name和id的方法:(通过contentWindow获取)


var iframe = document.getElementsByTagName('iframe')[0];\
var ifr_document = iframe.contentWindow.document;//iframe中的文档内容

或者:


var _iframe = document.getElementByIdx_x('iframeId').contentWindow;  

var _div =_iframe.document.getElementByIdx_x('objId'); **\
**

或者:


 var frameWin=document.getElementById('iframe').contentWindow;    //window对象  
 var frameDoc=document.getElementById('iframeId').contentWindow.document  //document对象  
 var frameBody=document.getElementById('iframeId').contentWindow.document.body   //body对

第二种情况:iframe中存在name或者id的方法:(通过frames[]数组获取)

document.frames['iframe的name'].document.getElementById('元素的ID');

第三种情况:在iframe中获取父级页面的id元素 :

var obj=window.parent.document.getElementById('objId') ;

$(window.parent.document).find("#objId").css('height':'height);   // window可省略不写 jquery

 

第四种情况:父级窗体访问iframe中的属性

a、 用contentWindow方法   
document.getElementById('iframe1').onload=function(){  
          this.contentWindow.run();  
  }  
 b、用iframes[]框架集数组方法  
document.getElementById('iframe1').onload=function(){             frames["iframe1"].run();  
} 
  

第五种情况:在iframe中访问父级窗体的方法和属性 //window 可以不写

  1. window.parent.attributeName;  // 访问属性attributeName是在父级窗口的属性名  
  2. window.parent.Func();  // 访问属性Func()是在父级窗口的方法 

 

第五种情况:让iframe自适应高度

  1. $('#iframeId').load(function() { //方法1  
  2.     var iframeHeight = Math.min(iframe.contentWindow.window.document.documentElement.scrollHeight, iframe.contentWindow.window.document.body.scrollHeight);  
  3.     var h=$(this).contents().height();  
  4.     $(this).height(h+'px');   
  5. });  
  6.   
  7. $('#iframeId').load(function() { //方法2  
  8.     var iframeHeight=$(this).contents().height();  
  9.     $(this).height(iframeHeight+'px');   
  10. });