img onload事件绑定,在IE或者Safari中不会执行onload事件

前端的一些坑

Winter

2018-06-24

一般来说绑定事件都是如下这样

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

  <title>img onload事件绑定(错误用法)</title>

</head>

<body>

  <img src='images/06.jpg' id='imgId'/>

</body>

<script type='text/javascript'>

  var img = document.getElementById('imgId');

  img.onload = function(){

      alert(1);

  };

</script>

</html>

发现alert(1)并没有执行,特别是在ie和ff浏览器下。而且在用到jquery插件库的时候会发现,alert除了在ie和Opera浏览器不弹出来外,其他浏览器均弹出来,这是为什么呢?!

第60篇《img onload事件绑定,在IE或者Safari中不会执行onload事件》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

1个回答
Winter 2018.06.25
主要是window.onload事件是在页面dom元素加载完后执行,也就包括了img图片中src加载完成。那么img.onload 就不会执行了,
因为其是监听img的src是否加载完成。
我们可以改成如下这样
var img = document.getElementById('imgId');
var src = img.getAttribute('src');
img.setAttribute('src','');
img.onload = function(){
alert(1);
};
img.setAttribute('src',src);
这种方法,在各浏览器下均执行alert(1)。
也就是在页面dom元素加载完成后,获得img的dom对象,获得其src属性,再将其src设置为‘’空,然后监听img的onload事件,最后再设置img的src属性即可。

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android