HTML onerror 事件属性

htmlweb developmentfront end technology更新于 2025/12/21 2:20:17

当 HTML 文档中加载外部文件发生错误时,会触发 HTML onerror 事件属性。

语法

以下是语法 −

<tagname onerror=”script”>Content</tagname>

让我们看一个 HTML onerror 事件属性的示例 −

示例

<!DOCTYPE html>
<html>
<head>
<style>
   body {
      color: #000;
      height: 100vh;
      background: linear-gradient(62deg, #FBAB7E 0%, #F7CE68 100%) no-repeat;
      text-align: center;
      padding: 20px;
   }
   .btn {
      background: #db133a;
      border: none;
      height: 2rem;
      border-radius: 2px;
      width: 40%;
      display: block;
      color: #fff;
      outline: none;
      cursor: pointer;
      margin: 1rem auto;
   }
</style>
</head>
<body>
<h1>HTML onerror Event Attribute Demo</h1>
<button onclick="add()" class="btn">Add Nature Image</button>
<script>
   function add() {
      var imgEle = document.createElement('IMG');
      imgEle.setAttribute("src", "nature.png");
      imgEle.setAttribute("alt", "nature image");
      imgEle.setAttribute("onerror", "errorFn()");
      document.body.appendChild(imgEle);
   }
   function errorFn() {
      document.body.style.background = "linear-gradient(45deg, #8BC6EC 0%, #9599E2 100%) no-repeat";
      document.body.style.color = "#fff";
   }
</script>
</body>
</html>

输出

点击“添加自然图像”按钮创建一个具有错误源属性和 onerror 事件属性的图像元素,然后将其添加到 body 元素。


相关文章


有用资源