使用者拉伸(使用者拉伸盒子變寬)
隻拉伸右邊,左側不動(就是盒子拉伸時top,left不動)
基于前兩篇,就直接粘貼全部代碼
css html沒有做改變,可以自己寫,也可以去前面看
var box = document.querySelector(".box");
var a = document.querySelector("#a");
// 盒子寬高
var boxHeight = box.offsetHeight,
boxWidth = box.offsetWidth;
// 滑鼠在盒子上移動時
a.onmousemove = e => {
// 盒子到螢幕左邊,上邊的距離,,和滑鼠位置
let left = getAbsLeft(a), top = getAbsTop(a), x = e.clientX, y = e.clientY;
// 右下角拉伸
if(width + left - x < 9 && height + top - y < 9 ){
a.style.cursor = "se-resize";
this.onmousedown = function(e) {
lashen(e,left,top)
};
}
// 右側拉伸
else if (width + left - x < 9 ) {
a.style.cursor = "e-resize";
this.onmousedown = function(e) {
you(e,left)
};
}
// 下側拉伸
else if(height + top - y < 9 ){
a.style.cursor = "s-resize";
this.onmousedown = function(e) {
xia(e,top)
};
}
// 拖拽
else{
a.style.cursor = "move"
this.onmousedown =function(e) {
tuozhuai(e)
};
}
}
// 擷取盒子到螢幕左方的距離
function getAbsLeft(obj){
var l=obj.offsetLeft;
while(obj.offsetParent != null){
obj = obj.offsetParent;
l += obj.offsetLeft;
}
return l;
}
// 擷取盒子到螢幕上方的距離
function getAbsTop(obj){
var top=obj.offsetTop;
while(obj.offsetParent != null){
obj = obj.offsetParent;
top += obj.offsetTop;
}
return top;
}
// 向右拉伸
function you(e,left) {
var width = a.offsetWidth;
var nowX = e.clientX;
document.onmousemove = function (e) {
e = e || window.event;
var aa = width + e.clientX - nowX;
aa = aa + left > boxWidth?boxWidth - left:aa;
a.style.width = aa + "px"
}
}
// 像下拉伸
function xia(e,top) {
var height = a.offsetHeight;
var nowY = e.clientY;
document.onmousemove = function (e) {
e = e || window.event;
var bb = height + e.clientY - nowY;
bb = bb + top > boxHeight?boxHeight - top:bb;
a.style.height = bb + "px";
}
}
// 右下角拉伸
function lashen(e,left,top) {
var width = a.offsetWidth;
var height = a.offsetHeight;
var nowX = e.clientX;
var nowY = e.clientY;
document.onmousemove = function (e) {
e = e || window.event;
var aa = width + e.clientX - nowX;
var bb = height + e.clientY - nowY;
aa = aa + left > boxWidth?boxWidth - left:aa;
bb = bb + top > boxHeight?boxHeight - top:bb;
a.style.width = aa + "px"
a.style.height = bb + "px";
}
}
// 拖拽事件
function tuozhuai(e){
// 盒子到父級的距離
let left = a.offsetLeft, top = a.offsetTop;
// 擷取盒子寬
var width = a.offsetWidth;
var height = a.offsetHeight;
//擷取x坐标和y坐标
var nowX = e.clientX;
var nowY = e.clientY;
document.onmousemove = function(e) {
// 需要移動的 x y
var nx = e.clientX - nowX;
var ny = e.clientY - nowY;
//計算移動後的左偏移量和頂部的偏移量
var nl = left + nx;
var nt = top + ny;
// 判斷出界
nl = nl + width > boxWidth?boxWidth - width:nl;
nl = nl < 0 ?0:nl;
nt = nt + height > boxHeight?boxHeight - height:nt;
nt = nt < 0 ?0:nt;
// 設定盒子left top
a.style.left = nl + 'px';
a.style.top = nt + 'px';
}
}
document.onmouseup = function () {
document.onmousemove = null;
}