在iframe上使用onerror

时间:2018-10-04 05:22:03

标签: javascript html css onerror

如果链接断开或不存在,则以下代码片段将PNG图像替换为GIF图像。我尝试将其应用于iframe,但似乎无法正常工作。这有可能吗?

<html>

	<body>

	<iframe src="index1.html" onerror="this.onerror=null;this.src='https://media.giphy.com/media/3oEjI6SIIHBdRxXI40/giphy.gif';"> </iframe>
	<img src="test.png" onerror="this.onerror=null;this.src='https://media.giphy.com/media/3oEjI6SIIHBdRxXI40/giphy.gif';" />

	</body>

</html>

非常感谢您的答复。提前致谢! :)

1 个答案:

答案 0 :(得分:0)

  

如果在加载外部文件(例如文档或图像)时发生错误,则会触发onerror事件。

iframe内容不是文件,因此不会触发错误。您可以使用JS检查是否收到HTTP成功响应(200)。

var myRequest = new Request('index1.html');

fetch(myRequest).then(function(response) {
  console.log(response.status); // returns 200
}).catch(function(error) {
  document.getElementById("iframe-id").src = "/your/file/path/here/somePage.html";
});
<iframe id="iframe-id" src="index1.html"> </iframe>
<img src="test.png" onerror="this.onerror=null;this.src='https://media.giphy.com/media/3oEjI6SIIHBdRxXI40/giphy.gif';" />