JSFiddle - React, Tailwind, and code Playground
by wang lei
HTML
<!-- <div class="box">
<div class="children" id="move"></div>
</div> -->
<div id="box">
<span id="children" style="position:absolute;left: 100px;top: 100px; width: 100px;height: 80px;background: red;"></span>
</div>
CSS
#box {
width: 1000px;
height: 600px;
background: #ccc;
}
JavaScript
var qwe = document.getElementById('box');
var rec = document.getElementById("children")
var data = {
dw: '',//存储默认的div的宽度。
dh: '',//存储默认的div的高度。
disright: '',//存储默认div右边距离屏幕左边的距离。
distop: '',//存储默认div上边距离屏幕左边的距离。
dx: '',//当你第一次单击的时候,存储x轴的坐标。
dy: '',//当你第一次单击的时候,储存Y轴的坐标。
disright:''
}
var go = ''
rec.onmousemove = function(e){
var ev =e||event;
str = variablePointer(rec);
if (str === "move") str = "move";
else str += "-resize";
rec.style.cursor = str;
go = str
}
rec.onmousedown = function (e) {
var ev =e||event;
data.dw=rec.offsetWidth;//存储默认的div的宽度。
data.dh=rec.offsetHeight;//存储默认的div的高度。
data.disright=rec.offsetLeft+rec.offsetWidth;//存储默认div右边距离屏幕左边的距离。
data.distop=rec.offsetHeight+rec.offsetTop;//存储默认div上边距离屏幕左边的距离。
data.dx=ev.clientX;//当你第一次单击的时候,存储x轴的坐标。
data.dy=ev.clientY;//当你第一次单击的时候,储存Y轴的坐标。
qwe.onmousemove = function (e) {
var ev =e||event;
if(go === 'w-resize') {
// 向左加width div 原宽 - (当前左边与文档区域的距离 - 原来左边与文档距离)
/* 120 = 100 - (80-100) */
rec.style.width=data.dw-(ev.clientX-data.dx)+'px';
// 原左偏移的值+ diw宽 - 现在div的宽
console.log(data.disright, rec.offsetWidth)
rec.style.left=data.disright-rec.offsetWidth+'px';
}
if(go === 'e-resize') {
rec.style.width=data.dw+(ev.clientX-data.dx)+'px';
}
}
rec.onmouseup=function(){
qwe.onmousemove=null;
};
return false;
}
function variablePointer(el) {
var xPos,
yPos,
offset,
dir;
dir = "";
xPos = window.event.offsetX; // 鼠标移动与dom左边的距离
yPos = window.event.offsetY;// 鼠标移动与dom上边的距离
offset = 10; // 设置差值
// 根据坐标大小添加鼠标指针
if(el.tagName === 'SPAN'){
// 如果鼠标移动的y轴距离小于差值dir = n
if (yPos<offset) {
dir +=...