IE8-浏览器下iframe的动态onload事件处理

先上代码:

<html>
  <head></head>
  <body>
    <iframe src="http://www.w3school.com.cn/i/eg_landscape.jpg" id='iframe1'></iframe> 
  </body>
</html>
<script>
  var iframe = document.getElementById('iframe1');
  iframe.onload=function(){
    alert('static');
  }
  setTimeout(function(){iframe.src = 'http://www.qiyipic.com/common/fix/records.png';},2000);
</script>

测试环境:IE8浏览器

期待效果:页面刚加载完时alert一下,2s之后再alert一下

实际效果:只在页面刚加载完时alert了一下,2s之后并没有alert

原因分析:IE8及以下浏览器不支持iframe的动态onload事件处理(img支持),也就是给它的src属性重新赋值

解决办法:在IE下时,用attachEvent绑定事件

<html>
  <head></head>
  <body>
    <iframe src="http://www.w3school.com.cn/i/eg_landscape.jpg" id='iframe1'></iframe> 
  </body>
</html>

<script>
  var iframe = document.getElementById('iframe1');
  if(iframe.attachEvent){
    iframe.attachEvent('onload',function(){
        alert('ok');
    });    
  }else{
    iframe.onload=function(){
      alert('ok');
    }    
  }
  setTimeout(function(){iframe.src = 'http://www.qiyipic.com/common/fix/records.png';},2000);
</script>

 PS:attachEvent只在低版本IE浏览器中被兹磁(zici,你问我兹磁不兹磁,我是兹磁的,写博客也要遵循基本法),且事件type前要加on,现代浏览器都用addEventListener

参考链接:http://blog.csdn.net/frankwangzy1103/article/details/6852259

原文地址:https://www.cnblogs.com/wangxuehao/p/6894664.html