JavaScript系列---【常用鼠标事件】

鼠标事件类型

1.1 onclick 单击

代码示例:

document.getElementById("box").onclick = function(){
 alert('onclick');
}

1.2 ondblclick 双击

代码示例:

document.getElementById("box").ondblclick = function(){ 
 alert('ondblclick');
 } 

1.3 onmouseover 鼠标移入

代码示例:

document.getElementById("box").onmouseover = function () { 
 alert('onmouseover'); 
}

1.4 onmouseout 鼠标移出

代码示例:

document.getElementById("box").onmouseout = function () { 
 alert('onmouseout');
 }

1.5 onmouseenter 鼠标进入

代码示例:

document.getElementById("box").onmouseenter = function () {
 alert('onmouseenter'); 
 }

1.6 onmouseleave 鼠标离开

代码示例:

document.getElementById("box").onmouseleave = function () { 
 alert('onmouseleave');
 }

1.7 onmousemove 鼠标移动

代码示例:

document.getElementById("box").onmousemove = function () { 
 alert('onmousemove'); 
 }

1.8 oncontextmenu 鼠标右击

代码示例:

document.getElementById("box").oncontextmenu = function () { 
 alert('oncontextmenu'); 
 }

1.9 onmousedown 鼠标按下

代码示例:

document.getElementById("box").onmousedown = function () { 
 alert('onmousedown'); 
 }

2.0 onmouseup 鼠标抬起

代码示例:

document.getElementById("box").onmouseup = function () { 
 alert('onmouseup'); 
 }

2.1 注意事项

鼠标移入及进入 - 移出及离开的区别:

onmouseover及onmouseout 不仅会将当前这个元素上这个事件触发还会将父元素对应的这个事件触发

<body>
    <!-- 父级元素 -->
    <div id="father">
        <!-- 子集元素 -->
        <div id="son"></div>
    </div>
    <script>
     document.getElementById("father").onmouseover = function(){
     console.log("father");//打印father
     }

     document.getElementById("son").onmouseout = function(){
     console.log("son");//打印son father
     }

     document.getElementById("father").onmouseenter = function(){
     console.log("father");
     }

     document.getElementById("son").onmouseenter = function(){
     console.log("son");
     }
    </script>
</body>

onmouseenter及onmouseleave 只会触发当前这个元素上的这个事件,不会触发父级元素当前这个事件

   document.getElementById("father").onmouseenter = function(){
   console.log("father");//打印father
   }

  document.getElementById("son").onmouseleave = function(){
  console.log("son");//打印son
  }
    

posted on 2021-02-22 23:19  码农小小海  阅读(137)  评论(0编辑  收藏  举报

导航