onLoad与onerror函数冲突

奥斯汀·柯林斯(Austin Collins)

创建一个简单的状态检查器,但是,当图像加载失败并且src更改为脱机符号时,onLoad函数将被触发并将图像更改为在线,即使网站处于脱机状态也是如此。

我知道我可以通过在要测试的网站上托管在线符号来解决此问题,但是我希望能够测试我不拥有或不喜欢在您的域中未托管图片的Blogger的网站。

<!DOCTYPE html>
<html>
    <head>
        <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico"/>
        <meta http-equiv="content-type" content="text/html; charset=utf-8" />
        <title>
            eTree Status
        </title>

    </head>
    <body>
        <div style="margin: 20px; background-color: #EEE; width: 400px; padding: 10px;">
            <img style="height:20px;" src="http://s.etree.biz/1AKeMjI" alt="status" onLoad="this.src='http://s.etree.biz/1E94ZDh'" onerror="this.src='http://s.etree.biz/1zQwvPm'" />
             blog.etree.biz
             <br/>
            <img style="height:20px;" src="http://s.etree.biz/1G7agdE" alt="status" onLoad="this.src='http://s.etree.biz/1E94ZDh'" onerror="this.src='http://s.etree.biz/1zQwvPm'" />
             www.etree.biz
             <br />
        </div>
    </body>
</html>
安德鲁·杜奈(Andrew Dunai)

如前所述,您的代码中的问题是,onload您在中分配成功/错误图片后会触发onerror,因此您可以将其禁用。

为此,只需清除onload内部处理程序onerroronload处理程序,例如:

<img src="http://example.org/image.png"
     onload="this.onload=null; this.src='success.png'"
     onerror="this.onload=null; this.src='error.png'">

编辑:如果您需要在加载远程图像时显示一些实际的微调器,则可以使用一个img显示微调器成功/错误图像,而使用另一种img实际检索远程img(触发onloadonerror

这是一个例子:

<!-- unexisting site or broken IMG -->
<div>
    <img id="state-1" src="http://www.xiconeditor.com/image/icons/loading.gif" />
    <img src="http://unexisting.com/"
         style="display: none"
         onload="document.getElementById('state-1').src = 'https://education.skype.com/assets/guest-speaker-signup/success-icon-255193729c9e0a50b2d36055359dd877.png';"
         onerror="document.getElementById('state-1').src = 'http://creativity-online.com/assets/images/sprites-retina/icon-error.png';" />
    Site 1
</div>

<!-- existing site with existing IMG -->
<div>
    <img id="state-2" src="http://www.xiconeditor.com/image/icons/loading.gif" />
    <img src="http://www.coffeecup.com/images/icons/applications/web-image-studio_128x128.png"
         style="display: none"
         onload="document.getElementById('state-2').src = 'https://education.skype.com/assets/guest-speaker-signup/success-icon-255193729c9e0a50b2d36055359dd877.png';"
         onerror="document.getElementById('state-2').src = 'http://creativity-online.com/assets/images/sprites-retina/icon-error.png';" />
    Site 2
</div>

...这是工作中的小提琴:http : //jsfiddle.net/andunai/2s2qeuyd/

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章