js
Directorio de artículos
prefacio
以下是鼠标事件,点击盒子拖动。
# 1. Pasos a seguir
1. El código es el siguiente.
El código es el siguiente (ejemplo):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
#box1 {
background-color: chartreuse;
position: fixed;
top: 0;
left: 0;
}
#box2 {
background-color: crimson;
position: fixed;
top: 0;
right: 0;
}
.box {
width: 300px;
height: 300px;
}
</style>
</head>
<body>
<div id="box1" class="box"></div>
<div id="box2" class="box"></div>
<script>
document.querySelectorAll('.box').forEach(box => {
box.onmousedown = function (e) {
// console.log(e.clientX,e.clientY);//当时事件触发时,鼠标距离屏幕的xy轴距离
// console.log(this.offsetLeft, this.offsetTop);//当前盒子距离屏幕xy轴的距离
let disX = e.clientX - this.offsetLeft,
disY = e.clientY - this.offsetTop;
document.onmousemove = function (e) {
let left = e.clientX - disX,
top = e.clientY - disY;
box.style.left = left + 'px';
box.style.top = top + 'px';
}
document.onmouseup = function(e){
document.onmousemove = null;
document.onmouseup = null;
}
}
})
</script>
</body>
</html>
Resumir
Este artículo solo presenta brevemente el uso del evento onmousedown.