鼠标事件,我的代码出了什么问题

mouse events, whats wrong in my code

本文关键字:什么 问题 代码 事件 我的 鼠标      更新时间:2023-09-26

在html部分中,我不想包含与事件相关的代码,与事件有关的代码应该在脚本标记中

<!doctype html>
  <head>
   <style>
      div{
           width:200px;
           background-color:grey;
         }
   </style>
   <body>
       <p>use the below area for events</p>
       <div> point here </div>  
       <a id="event_output"></a>
      <script>
         var output=document.getElementById("event_output").innerHTML;
         var div=document.getElementsByTagName("div");
         div[0].onmouseover=function(){output="mouse over"}
         div[0].onmouseout=function(){output="mouse out"}
      </script>                  
         
   </body>

您只是在更新作为字符串的output变量。而是存储对象引用并设置其innerHTML属性。

<style>
  div {
    width: 200px;
    background-color: grey;
  }
</style>
<p>use the below area for events</p>
<div>point here</div>
<a id="event_output"></a>
<script>
  var output = document.getElementById("event_output");
  var div = document.getElementsByTagName("div");
  div[0].onmouseover = function() {
    output.innerHTML = "mouse over"
  }
  div[0].onmouseout = function() {
    output.innerHTML = "mouse out"
  }
</script>