注释可能不够详细,代码写的有点多,效果基本全部实现了。
记录定位值以及clientX,Y值和offsetX,Y值是关键
<!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>
* {
margin: 0;
padding: 0;
/* cursor: e-resize; */
}
#parent {
width: 100%;
height: 600px;
background: pink;
position: relative;
}
#son {
width: 200px;
height: 200px;
background: orange;
position: absolute;
}
</style>
</head>
<body>
<div id="parent">
<div id="son"></div>
</div>
<script>
var parent = document.getElementById('parent');
var son = document.getElementById('son');
//保存值,以用于判断
var _Text = '';
//记录子级盒子点击的X点坐标
var cliX = 0;
//记录子级盒子点击的Y点坐标
var cliY = 0;
//记录子级盒子的宽
var cliW = 0;
//记录子级盒子的高
var cliH = 0;
//通过父级滑动事件触发子盒子移动
parent.onmousemove = function (e) {
//switch语句判断鼠标点击在什么位置
switch (true) {
//点击的位置在子级中间时执行移动操作
case _Text == 'center':
//记录盒子当前位置的距离左边与上边的距离
var yunLeft = e.clientX - cliX;
var yuntop = e.clientY - cliY;
//进行判断,以此确定边界值
if (yunLeft <= 0) {
yunLeft = 0;
}
if (yunLeft >= parent.offsetWidth - son.offsetWidth) {
yunLeft = parent.offsetWidth - son.offsetWidth;
}
if (yuntop <= 0) {