原生js实现拖拽效果案例
程序员文章站
2022-06-28 13:19:51
主要事件:1、onmousedown:鼠标按下事件2、onmousemove:鼠标移动事件3、onmouseup:鼠标按键被松开事件三个事件分别绑定的对象:(1)onmousedown:绑定到要被拖拽元素上(2)onmousemove:绑定到document上,主要是为了防止鼠标移动过快,移出要拖拽的元素(3)onmouseup:绑定到document上,主要是为了防止鼠标移动过快,移出要被拖拽的元素,导致无法触发鼠标按键被松开事件基本思路:拖拽状态 = false鼠标在...
效果展示:
20201127-171256
主要事件:
1、onmousedown:鼠标按下事件
2、onmousemove:鼠标移动事件
3、onmouseup:鼠标按键被松开事件
三个事件分别绑定的对象:
(1)onmousedown:绑定到要被拖拽元素上
(2)onmousemove:绑定到document上,主要是为了防止鼠标移动过快,移出要拖拽的元素
(3)onmouseup:绑定到document上,主要是为了防止鼠标移动过快,移出要被拖拽的元素,导致无法触发鼠标按键被松开事件
基本思路:
拖拽状态 = false
鼠标在元素上按下的时候{
拖拽状态 = true
记录下鼠标的x和y坐标
记录下元素的x和y坐标
}
鼠标在元素上移动的时候{
如果拖拽状态为false就什么也不做。
如果拖拽状态是true,那么
元素y = 现在鼠标y - 原来鼠标y + 原来元素y
元素x = 现在鼠标x - 原来鼠标x + 原来元素x
}
鼠标按键在任何时候被松开{
拖拽状态 = 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" />
<link rel="stylesheet" href="./index.css">
<title>test</title>
</head>
<body>
<div class="container">
<div>drag</div>
<div class="drag-box" style="left:0;top:50%"></div>
</div>
<script type="text/javascript" src="./index.js"></script>
</body>
</html>
.container {
width: 100%;
height: 1500px;
background-color: #fff;
position: relative;
}
.drag-box {
width: 100px;
height: 100px;
background-color: pink;
position: fixed;
}
window.onload = function() {
let dragObj = document.getElementsByClassName("drag-box")[0]
let dragging = false,
mouseX, mouseY, objX, objY, diffX, diffY;
dragObj.onmousedown = function(event) {
dragging = true
mouseX = event.clientX;
mouseY = event.clientY;
objX = dragObj.offsetLeft; //元素的初始位置
objY = dragObj.offsetTop;
diffX = mouseX - objX; //相当于鼠标距物体左边的距离
diffY = mouseY - objY;
}
document.onmousemove = function(event) {
if (dragging) {
dragObj.style.left = event.clientX - mouseX + objX + "px";
dragObj.style.top = event.clientY - mouseY + objY + "px";
//设置边界
if ((event.clientX - diffX) <= 0) { //鼠标到浏览器左边距小于鼠标到obj的左边距
// 左边界
dragObj.style.left = 0 + "px";
}
//window.innerWidth浏览器显示区域的宽度,dragObj.offsetWidth物体宽度
else if ((event.clientX - diffX) > (window.innerWidth - dragObj.offsetWidth)) {
//右边界
dragObj.style.left = window.innerWidth - dragObj.offsetWidth + "px";
}
if ((event.clientY - diffY) <= 0) {
dragObj.style.top = 0 + "px";
} else if ((event.clientY - diffY) > (window.innerHeight - dragObj.offsetHeight)) {
dragObj.style.top = window.innerHeight - dragObj.offsetHeight + "px";
}
} else {
console.log("flase")
}
}
document.onmouseup = function() {
dragging = false;
}
}
本文地址:https://blog.csdn.net/weixin_45899022/article/details/110237976
上一篇: 类C编译器 C代码实现
下一篇: Golang之变量去哪儿