<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
.move {
position: absolute;
width: 100px;
height: 100px;
background: gray
}
</style>
</head>
<body>
<div class="container">
<div class="move">
</div>
</div>
<script>
//获取待拖拽元素
let targetElem = document.querySelector('.move');
let windowHeight, windowWidth; //窗口宽高
let elemHeight, elemWidth; //元素宽高
let ifDrag; //拖拽标志
let moveLeft, moveTop; //鼠标按下时的位置相对选中元素的位置的位移;
//鼠标按下-主要完成获取位置坐标工作
document.addEventListener('mousedown', function(e){
if(e.target==targetElem){
//获取元素相对页面视口的位置,即初始位置(x,y坐标=左上角顶点坐标)
let targetElemLocate = targetElem.getBoundingClientRect();
//激活拖拽标志
ifDrag = true;
//页面视口宽高(判断边界时使用)
windowHeight = document.documentElement.clientHeight;
windowWidth = document.documentElement.clientWidth;
//获取元素宽高(判断边界时使用)
elemHeight = targetElem.clientHeight;
elemWidth = targetElem.clientWidth;
//鼠标按下时和选中元素的坐标偏移量(初始偏移量,即鼠标和元素的距离,留待拖拽时使用)
elemX = e.clientX - targetElemLocate.left;
elemY = e.clientY - targetElemLocate.top;
}
})
//鼠标放开事件
document.addEventListener('mouseup', function(e){
ifDrag = false;
})
//监听鼠标移动事件
document.addEventListener('mousemove', function(e){
if(ifDrag){
// 鼠标移动后相对视口的位置-鼠标和选中元素的初始偏移量=选中元素当前坐标位置(相对视口)
let moveX = e.clientX - elemX;
let moveY = e.clientY - elemY;
targetElem.style.left = moveX + 'px';
targetElem.style.top = moveY + 'px';
if(moveX<0){
// 超出左边界
targetElem.style.left = 0;
}
if(moveY<0){
// 超出上边界
targetElem.style.top = 0;
}
if(moveX + elemWidth > windowWidth){
// 超出右边界
targetElem.style.left = windowWidth - elemWidth + 'px';
}
if(moveY + elemHeight > windowHeight){
// 超出下边界
targetElem.style.top = windowHeight - elemHeight + 'px';
}
}
})
</script>
</body>
</html>
前端元素拖拽
最新推荐文章于 2024-06-01 13:39:13 发布