41 lines
1.4 KiB
TypeScript
41 lines
1.4 KiB
TypeScript
|
export function setMove(downId, moveID) {
|
||
|
let moveDiv = document.getElementById(downId)
|
||
|
moveDiv.style.cssText += ';cursor:move;'
|
||
|
let informationBox = document.getElementById(moveID)
|
||
|
const sty = (() => {
|
||
|
if (window.document.currentStyle) {
|
||
|
return (dom, attr) => dom.currentStyle[attr];
|
||
|
} else {
|
||
|
return (dom, attr) => getComputedStyle(dom, false)[attr];
|
||
|
}
|
||
|
})()
|
||
|
moveDiv.onmousedown = (e) => {
|
||
|
// 鼠标按下,计算当前元素距离可视区的距离
|
||
|
const disX = e.clientX - moveDiv.offsetLeft;
|
||
|
const disY = e.clientY - moveDiv.offsetTop;
|
||
|
// 获取到的值带px 正则匹配替换
|
||
|
let styL = sty(informationBox, 'left');
|
||
|
let styT = sty(informationBox, 'top');
|
||
|
// 第一次获取到的值为组件自带50% 移动之后赋值为px
|
||
|
if (styL.includes('%')) {
|
||
|
styL = +document.body.clientWidth * (+styL.replace(/\%/g, '') / 100);
|
||
|
styT = +document.body.clientHeight * (+styT.replace(/\%/g, '') / 100);
|
||
|
} else {
|
||
|
styL = +styL.replace(/\px/g, '');
|
||
|
styT = +styT.replace(/\px/g, '');
|
||
|
}
|
||
|
document.onmousemove = function (e) {
|
||
|
// 通过事件委托,计算移动的距离
|
||
|
let left = e.clientX - disX;
|
||
|
let top = e.clientY - disY;
|
||
|
// 移动当前元素
|
||
|
informationBox.style.cssText += `;left:${left + styL}px;top:${top + styT}px;`;
|
||
|
};
|
||
|
document.onmouseup = function (e) {
|
||
|
document.onmousemove = null;
|
||
|
document.onmouseup = null;
|
||
|
};
|
||
|
}
|
||
|
}
|
||
|
|