function getPos(obj) {
return obj.getBoundingClientRect();
}
class DragResize {
constructor(obj) {
// this.rightBottom = obj.rightBottom || true;
this.currentDrag = obj.currentDrag;
this.isDown = false;
}
init() {
this.handerMove();
this.handerMoveDrag();
this.cancle()
}
handerMove() {
let that = this;
this.currentDrag.onmousedown = function (ev) {
that.isDown = true;
that.mes = {
x: ev.clientX,
y: ev.clientY,
w: getPos(this).width,
h: getPos(this).height,
l: getPos(this).left,
t: getPos(this).top,
r: getPos(this).right,
b: getPos(this).bottom,
};
};
}
handerMoveDrag() {
let that = this;
let dir = '';
document.onmousemove = (ev) =>{
debugger
if (!that.isDown) {
//这个条件成立说明鼠标没有按下,只改变鼠标的样式
this.currentDrag.style.cursor = 'auto';
dir = '';//清空
//上
if (ev.clientY < getPos(this.currentDrag).top + 10) {
dir += 'n';
}
//下
if (ev.clientY > getPos(this.currentDrag).bottom - 10) {
dir += 's';
}
//左
if (ev.clientX < getPos(this.currentDrag).left + 10) {
dir += 'w';
}
//右
if (ev.clientX > getPos(this.currentDrag).right - 10) {
dir += 'e';
}
this.currentDrag.style.cursor = dir + '-resize'; //改变鼠标样式
} else {
//改变盒子的样式
if (dir.indexOf('e') != -1) {
//这个条件成立说明现在是往右拖
debugger
//w=原来的宽(mes.w)+拖动的距离(ev.clientX-mes.x)
var w = this.mes.w + ev.clientX - this.mes.x;
// console.log(w);
if (w < 100) {
w = 100;
}
this.currentDrag.style.width = w + 'px';
}
//往下拖
if (dir.indexOf('s') != -1) {
var h = this.mes.h + ev.clientY - this.mes.y;
// console.log(w);
if (h < 100) {
h = 100;
}
this.currentDrag.style.height = h + 'px';
}
//往左拖
if (dir.indexOf('w') != -1) {
//w=原来的宽(mes.w)+拖动的距离(mes.x-ev.clientX)
//l=原来的距离(mes.l)-拖动的距离(mes.x-ev.clientX)
var w = this.mes.w + this.mes.x - ev.clientX;
var l = this.mes.l - (this.mes.x - ev.clientX);
// console.log(w);
if (w < 100) {
w = 100;
l = this.mes.r - 100;
}
this.currentDrag.style.width = w + 'px';
this.currentDrag.style.left = l + 'px';
}
//往上拖
if (dir.indexOf('n') != -1) {
//w=原来的宽(mes.w)+拖动的距离(mes.x-ev.clientX)
//l=原来的距离(mes.l)-拖动的距离(mes.x-ev.clientX)
var h = this.mes.h + this.mes.y - ev.clientY;
var t = this.mes.t - (this.mes.y - ev.clientY);
if (h < 100) {
h = 100;
t = this.mes.b - 100;
}
this.currentDrag.style.height = h + 'px';
this.currentDrag.style.top = t + 'px';
}
}
};
}
cancle() {
let that = this;
document.onmouseup = function () {
that.isDown = false;
};
}
}
let drag = new DragResize({ currentDrag: document.querySelector('#box') });
drag.init();
窗口拖拽resize
最新推荐文章于 2020-09-28 23:41:51 发布