关于js中的鼠标事件

一、 常用到的鼠标事件

类型事件
click单击鼠标左键时发生,如果右键也按下则不会发生
dbclick双击鼠标左键时发生,如果右键也按下则不会发生
mousedown单击任意一个鼠标按钮时发生
mouseout鼠标指针位于某个元素上且将要移出元素的边界时发生
mouseover鼠标指针移出某个元素到另一个元素上时发生
mouseup松开任意一个鼠标按钮时发生
mousemove鼠标在某个元素上时持续发生

二、 鼠标点击事件

鼠标点击事件包括 click(单击)、dblclick(双击)、mousedown(按下)和 mouseup(松开)四个。其中 click 事件类型比较常用,而 mousedown 和 mouseup 事件类型多用在鼠标拖放、拉伸操作中。当这些事件处理函数的返回值为 false 时,会禁止绑定对象的默认行为。

示例如下:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    .box{
      width: 100px;
      height: 100px;
      background-color: pink;
    }
  </style>
</head>
<body>
  <div class="box"></div>
</body>
<script>
  var box=document.querySelector('.box')
  box.onclick=function(){
    this.style.backgroundColor='skyblue'
    // 鼠标点击后盒子变蓝
  }
</script>
</html>

二、 鼠标经过事件

鼠标经过包括移过和移出两种事件类型。当移动鼠标指针到某个元素上时,将触发 mouseover 事件;而当把鼠标指针移出某个元素时,将触发 mouseout 事件。如果从父元素中移到子元素中时,也会触发父元素的 mouseover 事件类型。

示例如下:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    .box{
      width: 100px;
      height: 100px;
      background-color: pink;
    }
  </style>
</head>
<body>
  <div class="box"></div>
</body>
<script>
  var box=document.querySelector('.box')
  box.onmouseover=function(){
    this.style.backgroundColor='skyblue'
    // 鼠标移入后盒子变蓝
  }
  box.onmouseout=function(){
    this.style.backgroundColor='black'
    // 鼠标移出后盒子变黑
  }
</script>
</html>

二、 鼠标移动事件

mousemove 事件类型是一个实时响应的事件,当鼠标指针的位置发生变化时(至少移动一个像素),就会触发 mousemove 事件。该事件响应的灵敏度主要参考鼠标指针移动速度的快慢以及浏览器跟踪更新的速度。

示例如下:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    .box{
      width: 100px;
      height: 100px;
      background-color: pink;
    }
  </style>
</head>
<body>
  <div class="box"></div>
</body>
<script>
  var box=document.querySelector('.box')
  box.onmousemove=function(){
    this.style.backgroundColor='skyblue'
    // 鼠标在盒子内移动后盒子变蓝
  }

</script>
</html>

  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

努力搬砖丿

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值