JavaScript中常见的鼠标事件及应用场景
作者:我自纵横2023
一. 基础交互事件
1. click
触发时机:
当用户在元素上按下并释放鼠标主按钮(通常是左键)时触发。
应用场景:
常用于处理按钮点击、链接跳转、表单提交等操作。
示例代码:
<!DOCTYPE html> <html lang="en"> <body> <button id="myButton">点击我</button> <script> const button = document.getElementById('myButton'); button.addEventListener('click', function () { alert('按钮被点击了!'); }); </script> </body> </html>
2. dblclick
触发时机:
当用户在短时间内快速连续点击两次鼠标主按钮时触发。
应用场景:
可用于实现双击放大图片、编辑文本等功能。
示例代码:
<!DOCTYPE html> <html lang="zh-CN"> <head> <style> #myDiv { width: 200px; height: 200px; background-color: lightblue; /* 初始背景颜色 */ display: flex; /* 使用flex布局 */ justify-content: center; /* 水平居中 */ align-items: center; /* 垂直居中 */ font-size: 30px; font-weight: bold; } </style> </head> <body> <h1>双击鼠标事件,改变颜色</h1> <div id="myDiv">双击我,<br>改变颜色</div> <script> const div = document.getElementById('myDiv'); // 颜色数组 const color = ['lightblue', 'pink', 'lightgreen', 'lightyellow', 'lightgray']; // 初始化计数器为-1,以便第一次双击时颜色数组从索引0开始变化 let dblcount = -1; // 添加双击事件监听器 div.addEventListener('dblclick', function () { dblcount++; // 循环改变背景颜色 this.style.backgroundColor = color[dblcount % color.length]; }); </script> </body> </html>
二、按钮状态事件
3. mousedown
触发时机:
当用户在元素上按下任意鼠标按钮时触发。
应用场景:
常用于实现拖动元素、绘制图形等操作的起始点。
示例代码:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Untitled-1</title> </head> <body> <h1>鼠标事件-按下</h1> <div id="draggable" style="width:100px;height:100px;background-color:red;">拖动我</div> <script> const draggable = document.getElementById('draggable'); draggable.addEventListener('mousedown', function () { console.log('鼠标按下'); draggable.style.backgroundColor = 'blue'; }); </script> </body> </html>
4. mouseup
触发时机:
- 当用户在元素上释放之前按下的鼠标按钮时触发。
应用场景:
- 通常与
mousedown
事件配合使用,用于完成拖动、绘制等操作。
示例代码:
<!DOCTYPE html> <html lang="en"> <body> <div id="drawArea" style="width: 200px; height: 200px; border: 1px solid black;"></div> <script> const drawArea = document.getElementById('drawArea'); drawArea.addEventListener('mousedown', function () { console.log('鼠标按下'); drawArea.style.backgroundColor = 'blue'; }); drawArea.addEventListener('mouseup', function () { console.log('鼠标释放'); drawArea.style.backgroundColor = 'red'; }); </script> </body> </html>
此代码的主要功能是通过监听鼠标在指定div
上的按下和释放事件,实现div
背景颜色的变化。具体来说:
- 当用户点击
div
时,div
的背景颜色会变为蓝色,同时在控制台输出“鼠标按下”。 - 当用户松开鼠标时,
div
的背景颜色会变为红色,同时在控制台输出“鼠标释放”。
这段代码主要用于演示如何使用JavaScript的事件监听机制来响应用户的鼠标操作,并实时更新网页元素的样式。
三、鼠标移动事件
5. mousemove
触发时机:
- 当鼠标指针在元素上移动时,会持续触发该事件。
应用场景:
- 常用于实现鼠标跟随效果、绘制轨迹、实时更新鼠标位置信息等。
示例代码:
<!DOCTYPE html> <html lang="en"> <body> <div id="moveArea" style="width: 200px; height: 200px; border: 1px solid black;"></div> <p>请在黑色区域内移动鼠标,并查看下面的鼠标位置。</p> <p>鼠标位置: (0, 0)</p> <script> const moveArea = document.getElementById('moveArea'); moveArea.addEventListener('mousemove', function (event) { console.log(`鼠标位置: (${event.offsetX}, ${event.offsetY})`); // 使用querySelector选择页面中最后一个<p>标签,并将其文本内容更新为当前鼠标的位置。 document.querySelector('p:last-of-type').textContent = `鼠标位置: (${event.offsetX}, ${event.offsetY})`; }); </script> </body> </html>
这段代码的主要功能是在网页上创建一个200x200像素的黑色边框区域,并实时显示用户在这个区域内的鼠标位置。每当鼠标在该区域内移动时,位置信息会被更新到页面上的最后一个段落标签中,并且在控制台中输出。
6. mouseover、mouseout
触发时机:
mouseover
当鼠标指针从元素外部移动到元素内部时触发,并且当鼠标进入该元素的子元素时也会触发。mouseout
当鼠标指针从元素内部移动到元素外部时触发,并且当鼠标离开该元素的子元素时也会触发。
应用场景:
mouseover
常用于实现鼠标悬停效果,如显示下拉菜单、改变元素样式等。mouseout
通常与mouseover
事件配合,用于恢复元素的原始样式。
示例代码:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>鼠标悬停切换类</title> <style> /* 设置div的基本样式 */ div { position: relative; display: inline-block; place-content: center; text-align: center; font-size: 20px; color: white; cursor: pointer; } /* 定义原始样式 */ .original { width: 180px; height: 180px; background-color: lightgray; } /* 定义悬停时的样式 */ .hovered { width: 180px; height: 180px; background-color: pink; border: 2px solid black; } </style> </head> <body> <!-- 创建一个div元素,初始应用original样式 --> <div id="element" class="original">悬停切换样式</div> <script> // 获取id为element的div元素 const element = document.getElementById('element'); // 添加鼠标悬停事件监听器,切换到hovered样式 element.addEventListener('mouseover', function () { this.classList.remove('original'); this.classList.add('hovered'); }); // 添加鼠标移出事件监听器,切换回original样式 element.addEventListener('mouseout', function () { this.classList.remove('hovered'); this.classList.add('original'); }); </script> </body> </html>
这段代码的主要功能是在网页上实现一个简单的鼠标悬停效果。当用户将鼠标悬停在特定的div元素上时,该元素的背景颜色会从浅灰色变为粉色,并且增加一个黑色边框。当鼠标移开时,div元素的样式会恢复到原来的浅灰色背景无边框状态。这是一种常见的交互设计,用于提高用户体验,通过视觉反馈来告知用户他们与页面元素的交互状态。
<!DOCTYPE html> <html lang="zh"> <head> <meta charset="UTF-8"> <title>悬停下拉菜单示例</title> <style> .menu { list-style-type: none; margin: 0; padding: 0; } .menu-item { position: relative; display: inline-block; } .menu-item a { display: block; padding: 10px; color: #fff; background-color: #007BFF; text-decoration: none; } .submenu { display: none; position: absolute; top: 100%; left: 0; background-color: #007BFF; list-style-type: none; margin: 0; padding: 0; box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2); } .submenu li { width: 200px; } .submenu li a { padding: 12px 16px; text-decoration: none; display: block; color: white; } .submenu li a:hover { background-color: #555; } </style> </head> <body> <ul class="menu"> <li class="menu-item"> <a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >菜单项1</a> <ul class="submenu"> <li><a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >子菜单项1-1</a></li> <li><a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >子菜单项1-2</a></li> <li><a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >子菜单项1-3</a></li> </ul> </li> <li class="menu-item"> <a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >菜单项2</a> <ul class="submenu"> <li><a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >子菜单项2-1</a></li> <li><a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >子菜单项2-2</a></li> <li><a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >子菜单项2-3</a></li> </ul> </li> </ul> <script> document.addEventListener('DOMContentLoaded', function () { const menuItems = document.querySelectorAll('.menu-item'); menuItems.forEach(function (item) { item.addEventListener('mouseover', function () { const submenu = this.querySelector('.submenu'); if (submenu) { submenu.style.display = 'block'; } }); item.addEventListener('mouseout', function () { const submenu = this.querySelector('.submenu'); if (submenu) { submenu.style.display = 'none'; } }); }); }); </script> </body> </html>
下面是对 javascript 代码的逐步分解:
document.addEventListener('DOMContentLoaded', function () { ... });
- 这行代码的作用是监听整个文档是否已经完全加载完毕。只有在文档加载完成后,脚本中的内容才会被执行,确保在操作DOM元素时这些元素已经存在。
const menuItems = document.querySelectorAll('.menu-item');
- 使用
querySelectorAll
方法选择所有带有menu-item
类名的元素,并将它们存储在一个NodeList对象menuItems
中。在这个例子中,menuItems
包含了两个菜单项,即“菜单项1”和“菜单项2”。
- 使用
menuItems.forEach(function (item) { ... });
- 对于NodeList中的每一个元素(即每个菜单项),执行一次回调函数。回调函数中的参数
item
代表当前正在处理的菜单项。
- 对于NodeList中的每一个元素(即每个菜单项),执行一次回调函数。回调函数中的参数
item.addEventListener('mouseover', function () { ... });
- 为每个菜单项添加一个
mouseover
事件监听器。当鼠标进入菜单项时,会触发回调函数中的代码。
- 为每个菜单项添加一个
const submenu = this.querySelector('.submenu');
- 在
mouseover
事件的回调函数中,this
指向触发事件的菜单项。通过querySelector
方法,我们在这个菜单项内部查找第一个带有submenu
类名的元素,即子菜单。
- 在
if (submenu) { submenu.style.display = 'block'; }
- 如果找到了子菜单(即
submenu
不为null),则将它的display
属性设置为’block’,使子菜单显示出来。
- 如果找到了子菜单(即
item.addEventListener('mouseout', function () { ... });
- 为每个菜单项添加一个
mouseout
事件监听器。当鼠标离开菜单项时,会触发回调函数中的代码。
- 为每个菜单项添加一个
if (submenu) { submenu.style.display = 'none'; }
- 同样地,在
mouseout
事件的回调函数中,如果找到了子菜单,则将其display
属性设置为’none’,使子菜单隐藏起来。
- 同样地,在
7. mouseenter、mouseleave
触发时机:
mouseenter
当鼠标指针从元素外部移动到元素内部时触发,但当鼠标进入该元素的子元素时不会再次触发。mouseleave
当鼠标指针从元素内部移动到元素外部时触发,但当鼠标离开该元素的子元素时不会触发。
应用场景:
mouseenter
与mouseover
类似,但不会受子元素影响,适合需要精确控制悬停范围的场景。mouseleave
与mouseout
类似,但不会受子元素影响,常与mouseenter
配合使用。
示例代码:
<!DOCTYPE html> <html lang="zh"> <head> <meta charset="UTF-8"> <title>mouseenter 事件示例</title> <style> .tooltip { display: none; position: absolute; background-color: #007BFF; color: white; padding: 5px 10px; border-radius: 5px; font-size: 12px; } .button-container { position: relative; display: inline-block; } </style> </head> <body> <div class="button-container"> <button id="myButton">悬停我</button> <div class="tooltip" id="myTooltip">这是一个提示信息</div> </div> <script> document.addEventListener('DOMContentLoaded', function () { const button = document.getElementById('myButton'); const tooltip = document.getElementById('myTooltip'); button.addEventListener('mouseenter', function () { // 显示提示框 tooltip.style.display = 'block'; // 获取按钮的位置,并设置提示框的位置 const buttonRect = button.getBoundingClientRect(); tooltip.style.top = `${buttonRect.bottom + window.scrollY}px`; tooltip.style.left = `${buttonRect.left + window.scrollX}px`; }); button.addEventListener('mouseleave', function () { // 隐藏提示框 tooltip.style.display = 'none'; }); }); </script> </body> </html>
mouseenter
事件与 mouseover
事件的主要区别在于,mouseenter
不会冒泡到其子元素上,而 mouseover
会。这意味着当鼠标进入一个元素时,mouseenter
只会触发一次,而 mouseover
可能在鼠标进入子元素时再次触发。
mouseenter
事件最适合用于需要精确控制事件只在特定元素上触发的场景,而不需要考虑子元素的情况。例如,当你想要在鼠标进入某个按钮时显示一个提示,但不希望在子元素上重复显示这个提示时,可以使用 mouseenter
。
在上面的示例中,我们创建了一个按钮和一个提示框。当鼠标进入按钮区域时,使用 mouseenter
事件来显示提示框,并根据按钮的位置动态设置提示框的位置,确保提示框显示在按钮下方。当鼠标离开按钮区域时,使用 mouseleave
事件来隐藏提示框。
这里使用 mouseenter
和 mouseleave
事件而不是 mouseover
和 mouseout
事件,是为了避免当鼠标移动到按钮的子元素(如果有)时,提示框被重复显示或隐藏。在这个简单的例子中,按钮没有子元素,但如果有更复杂的结构,mouseenter
和 mouseleave
的非冒泡特性会更显优势。
四、鼠标滚轮事件
8. wheel
触发时机:
- 当用户滚动鼠标滚轮时触发。
应用场景:
- 常用于实现页面滚动、缩放元素、切换幻灯片等功能。
示例代码:
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>滚轮事件示例</title> <style> body { height: 2000px; /* 为了能看到滚动效果 */ } </style> </head> <body> <script> // 获取body元素 var body = document.body; // 添加滚轮事件监听器 body.addEventListener('wheel', function(event) { // 阻止默认行为 event.preventDefault(); // 判断滚轮滚动的方向 if (event.deltaY > 0) { console.log(event.deltaY); console.log('向下滚动'); } else { console.log('向上滚动'); } }); </script> </body> </html>
这段代码的主要功能是在网页的<body>
元素上添加一个滚轮事件监听器,用于检测用户鼠标滚轮的滚动方向,并在控制台中输出滚动方向的信息。需要注意的是,这段代码还阻止了页面的默认滚动行为,因此即使用户尝试滚动鼠标滚轮,页面也不会发生自动的上下滚动。
五、鼠标右键事件
9. contextmenu
触发时机:
- 当用户在元素上点击鼠标右键时触发。
应用场景:
- 可用于自定义上下文菜单,替代浏览器默认的右键菜单。
示例代码:
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>右击事件示例</title> <style> body { height: 2000px; /* 为了能看到滚动效果 */ position: relative; } #customMenu { display: none; position: absolute; background-color: #f9f9f9; border: 1px solid #d3d3d3; box-shadow: 2px 2px 5px rgba(0, 0, 0, 0.3); padding: 5px 0; width: 150px; z-index: 1000; } #customMenu div { padding: 8px 15px; cursor: pointer; } #customMenu div:hover { background-color: #ddd; } </style> </head> <body> <div id="customMenu"> <div onclick="showAlert('选项1')">选项1</div> <div onclick="showAlert('选项2')">选项2</div> <div onclick="showAlert('选项3')">选项3</div> </div> <script> // 获取body元素,以便在页面上添加事件监听器 var body = document.body; // 获取自定义菜单元素,该元素在用户右击时显示 var customMenu = document.getElementById('customMenu'); // 添加右击事件监听器 body.addEventListener('contextmenu', function (event) { // 阻止默认行为(显示浏览器的上下文菜单) event.preventDefault(); // 设置自定义菜单的位置为鼠标点击的位置 customMenu.style.left = event.pageX + 'px'; customMenu.style.top = event.pageY + 'px'; // 显示自定义菜单 customMenu.style.display = 'block'; }); // 添加点击页面其他地方隐藏菜单的事件监听器 document.addEventListener('click', function (event) { if (event.target !== customMenu) { customMenu.style.display = 'none'; } }); // 显示弹窗的函数,用于测试菜单选项 function showAlert(option) { alert('你点击了:' + option); } </script> </body> </html>
六、事件对象
在上述示例中,事件处理函数通常会接收一个事件对象作为参数(如 event
)。通过这个事件对象,可以获取与鼠标事件相关的信息,如鼠标的坐标、按下的按钮等。常见的属性包括:
clientX
和clientY
:鼠标相对于浏览器窗口可视区域的坐标。offsetX
和offsetY
:鼠标相对于触发事件的元素的坐标。button
:表示按下的鼠标按钮,0 代表左键,1 代表中键,2 代表右键。
这些鼠标事件为开发者提供了丰富的交互手段,可以根据具体需求灵活运用,打造出更加生动和交互性强的网页。
以上就是JavaScript中常见的鼠标事件及应用场景的详细内容,更多关于JavaScript鼠标事件及应用的资料请关注脚本之家其它相关文章!