HTML DOM 可取消事件属性

htmlweb developmentfront end technology更新于 2025/9/23 1:48:17

HTML DOM 可取消事件属性与 HTML 事件相关联,因为 JavaScript 可以对这些事件做出响应。可取消事件属性返回布尔值 true 或 false,指示该事件是否可以取消。

语法

以下是可取消事件属性的语法 −

event.cancelable

示例

让我们看一个可取消事件属性的示例 −

<!DOCTYPE html>
<html>
<body>
<p>Hover over the button below to find out if onmouseover is cancellable event or not</p>
<button onmouseover="cancelFunction(event)">CLICK IT</button>
<p id="Sample"></p>
<script>
   function cancelFunction(event) {
      var x = event.cancelable;
      if(x==true)
         document.getElementById("Sample").innerHTML = "The onmouseover event is cancellable";
      else
         document.getElementById("Sample").innerHTML = "The onmouseover event is not
      cancellable";

   }
</script>
</body>
</html>

输出

这将产生以下输出 −

鼠标悬停在"CLICK IT"按钮上时 −

我们首先创建了一个"CLICK IT"按钮,当鼠标悬停在"CLICK IT"按钮上时,它会将 ommouseover 事件对象传递给 cancellationFunction(event) 方法。

<button onmouseover="cancelFunction(event)>>CLICK IT</button>

cancelFunction(event) 方法检查传入事件对象的 event.cancelable 值,并将其赋值给变量 x。我们使用条件语句检查 event.cancelable 返回的是 true 还是 false,然后在 id 为"Sample"的段落标签中显示相应的消息 −

function cancelFunction(event) {
   var x = event.cancelable;
   if(x==true)
      document.getElementById("Sample").innerHTML = "The onmouseover event is cancellable";
   else
      document.getElementById("Sample").innerHTML = "The onmouseover event is not cancellable";
}

相关文章


有用资源