鼠标事件,我的代码中有什么错误

时间:2016-05-01 15:47:26

标签: javascript html

在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>

1 个答案:

答案 0 :(得分:1)

您只是更新output变量,这是一个字符串。而是存储对象引用并设置其innerHTML属性。

&#13;
&#13;
<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>
&#13;
&#13;
&#13;