电脑端的拖拽
<body style="margin: 0;">
<div class="body" style="height: 745px;width: 800px;background-color: red">
<div id="app" style="position:absolute; width:100px; height:100px; background:#3481B8;left: 100px;top: 70px;">
</div>
</div>
<script type="text/javascript">
var dragging = null, tLeft, tTop, appElement = document.getElementById("app");
// 鼠标点击事件
document.addEventListener("mousedown", function (event) {
if (event.target == appElement) {
dragging = true;
var target = event.target;
// 获取当前所点击位置,到当前元素左侧和顶部边界的差值
tLeft = event.clientX - target.offsetLeft;
tTop = event.clientY - target.offsetTop;
}
});
// 鼠标松开事件
document.addEventListener("mouseup", function (e) {
dragging = false;
});
// 鼠标移动事件
document.addEventListener("mousemove", function (e) {
if (dragging) {
var appX = e.clientX - tLeft,
appY = e.clientY - tTop;
// X轴右侧的极限
if(appX + document.getElementById("app").clientWidth > document.querySelector(".body").clientWidth){
appX = document.querySelector(".body").clientWidth - document.getElementById("app").clientWidth
// X轴左侧的极限
}else if(appX <= 0){
appX = 0
}
// Y轴底部极限
if(appY + document.getElementById("app").clientHeight > document.querySelector(".body").clientHeight){
appY = document.querySelector(".body").clientHeight - document.getElementById("app").clientHeight
// Y轴顶部极限
}else if(appY <= 0){
appY = 0
}
appElement.style.left = appX + "px";
appElement.style.top = appY + "px";
}
});
/*
event.target.offsetLeft:指元素左边距离其包含元素的距离
event.target.offsetTop:指元素上边距离其包含元素的距离
event.target.clientHeight:当前元素高度
event.target.clientWidth:当前元素宽度
event.clientX:鼠标按下时的x坐标
event.clientY:鼠标按下时的y坐标
*/
</script>
</body>
电脑端与手机端的区别:
- 在获取clientX、clientY等时,手机端需要在前加
targetTouches[0]
思路
- 在我们进行拖拽时,保存一个点击位置与top和left边界差值( tTop和tLeft ),在鼠标松开事件
mouseup
上去将新的X和Y值分别去减对应的tLeft和tTop - 在边界极限上,将想往外拖拽的元素,一直矫正为最小(往上/往左)或最大(往下/往右)的值
电脑端鼠标事件:
- mousedown: 鼠标点击事件
- mousemove: 鼠标移动事件
- mouseup:鼠标抬起事件
移动端鼠标事件:
- touchstart:鼠标点击事件
- touchmove:鼠标移动事件
- touchend:鼠标松开事件