鼠标事件
Tutorial: DOM实战
Category: JS
Published: 2026-04-07 13:58:26
Views: 20
Likes: 0
Comments: 0
一、鼠标事件
| 事件名称 | 描述 |
|---|
| onclick | 当单击鼠标时运行脚本 |
| ondblclick | 当双击鼠标时运行脚本 |
| ondrag | 当拖动元素时运行脚本 |
| ondragend | 当拖动操作结束时运行脚本 |
| ondragenter | 当元素被拖动至有效的拖放目标时运行脚本 |
| ondragleave | 当元素离开有效拖放目标时运行脚本 |
| ondragover | 当元素被拖动至有效拖放目标上方时运行脚本 |
| ondragstart | 当拖动操作开始时运行脚本 |
| ondrop | 当被拖动元素正在被拖放时运行脚本 |
| onmousedown | 当按下鼠标按钮时运行脚本 |
| onmousemove | 当鼠标指针移动时运行脚本 |
| onmouseout | 当鼠标指针移出元素时运行脚本 |
| onmouseover | 当鼠标指针移至元素之上时运行脚本 |
| onmouseup | 当松开鼠标按钮时运行脚本 |
| onmousewheel | 当转动鼠标滚轮时运行脚本 |
| onscroll | 当滚动元素滚动元素的滚动条时运行脚本 |
二、鼠标坐标
<!DOCTYPE html>
<html lang="en">
<head>
<style>
body {
height: 3000px;
}
</style>
</head>
<body>
<script>
document.addEventListener("click", function (e) {
console.log("x: ", e.clientX, "y: ", e.clientY);
console.log("---------------------");
console.log("pageX: ", e.pageX, "pageY: ", e.pageY);
console.log("---------------------");
console.log("screenX: ", e.screenX, "screenY: ", e.screenY);
});
</script>
</body>
</html>
三、跟随鼠标的天使
<!DOCTYPE html>
<html lang="en">
<head>
<style>
img {
position: absolute;
top: 2px;
}
</style>
</head>
<body>
<img src="images/angel.gif" alt="" />
<script>
var pic = document.querySelector("img");
document.addEventListener("mousemove", function (e) {
var x = e.pageX;
var y = e.pageY;
console.log("x坐标是" + x, "y坐标是" + y);
pic.style.left = x - 50 + "px";
pic.style.top = y - 40 + "px";
});
</script>
</body>
</html>