目录
(2)按下和松开事件(mousedown和mouseup):
(3)移动事件(mousemove,mouseenter和mouseleave):
(4)悬浮和离开事件(mouseover和mouseout):
(4)beforunload:当页面即将卸载时触发,用于执行一些清理操作。
(5)unload:当页面已经卸载时触发,用于执行一些清理操作
一、鼠标事件
1、概念:
鼠标事件是指当用户使用鼠标进行各种操作时,浏览器触发的一系列事件。这些事件允许开发者在用户与网页交互时执行特定的JavaScript代码。鼠标事件在Web开发中非常常见,因为鼠标是最常用的导航设备之一。
2、常见的鼠标事件类型
(1)点击事件(click
和dblclick
):
click
事件在用户按下鼠标键时触发(单击),而dblclick
在用户双击鼠标时触发。
<head>
<style>
.box{
width: 60px;
height: 30px;
background-color: aliceblue;
border: 2px solid black;
text-align: center;
}
body {
height: 3000px; /* 增加浏览器页面高度以便滚动 */
}
</style>
</head>
<body>
<div class="box" id="b1">
事件
</div>
<script>
// 为某个节点添加事件监听器
box = document.getElementById("b1");
box.addEventListener( "click",
function(){
console.log("你的鼠标单击了!");
}
);
box.addEventListener( "dblclick",
function(){
console.log("你的鼠标双击了!");
}
);
</script>
</body>
效果如下:
(2)按下和松开事件(mousedown和mouseup
):
mousedown
在用户按下鼠标键时触发,而mouseup
在用户释放鼠标键时触发。
<body>
<div class="box" id="b1">
事件
</div>
<script>
// 为某个节点添加事件监听器
box = document.getElementById("b1");
box.addEventListener( "mousedown",
function(){
console.log("你的鼠标按下了!");
}
);
box.addEventListener( "mouseup",
function(){
console.log("你的鼠标抬起了!");
}
);
</script>
</body>
效果如下:
(3)移动事件(mousemove,mouseenter和mouseleave
):
mousemove
在鼠标移动时触发,mouseenter
和mouseleave
分别在鼠标进入和离开元素时触发。
<body>
<div class="box" id="b1">
事件
</div>
<script>
box.addEventListener( "mouseenter",
function(){
console.log("你的鼠标进入目标元素了!");
}
);
box.addEventListener( "mouseleave",
function(){
console.log("你的鼠标离开目标元素了!");
}
);
</script>
</body>
效果如下:
(4)悬浮和离开事件(mouseover和mouseout
):
mouseover
在鼠标悬浮在元素或其子元素上时触发,而mouseout
在鼠标离开元素时触发。
<body>
<div class="box" id="b1">
事件
</div>
<script>
box.addEventListener( "mouseover",
function(){
console.log("你的鼠标悬浮在在元素或其子元素上了!");
}
);
box.addEventListener( "mouseout",
function(){
console.log("你的鼠标离开元素了!"