// 新增拖拽的方法
const dragFun = (event,isRecover,preRight,preBottom) => {
const dragDiv = event.target
const rightDistance = parseInt(dragDiv.style.right) // 获取当前的x右轴距离
const bottomDistance = parseInt(dragDiv.style.bottom) // 获取当前的y下轴距离
let innerX = document.documentElement.clientWidth - event.clientX - rightDistance // 获取鼠标在方块内的x右轴距
let innerY = document.documentElement.clientHeight - event.clientY - bottomDistance // 获取鼠标在方块内的y下轴距
// 鼠标移动的时候不停的修改div的right和bottom值
document.onmousemove = function (event) {
let right = document.documentElement.clientWidth - event.clientX;
let bottom = document.documentElement.clientHeight - event.clientY;
dragDiv.style.right = right - innerX + 'px'
dragDiv.style.bottom = bottom - innerY + 'px'
// 边界判断
if (parseInt(dragDiv.style.right) <= 0) {
dragDiv.style.right = '0px'
}
if (parseInt(dragDiv.style.bottom) <= 0) {
dragDiv.style.bottom = '0px'
}
if (
parseInt(dragDiv.style.left) >=
window.innerWidth - parseInt(dragDiv.style.width)
) {
dragDiv.style.left =
window.innerWidth - parseInt(dragDiv.style.width) + 'px'
}
if (
parseInt(dragDiv.style.top) >=
window.innerHeight - parseInt(dragDiv.style.height)
) {
dragDiv.style.top =
window.innerHeight - parseInt(dragDiv.style.height) + 'px'
}
}
// 鼠标抬起时,清除绑定在文档上的mousemove和mouseup事件
document.onmouseup = function () {
document.onmousemove = null
document.onmouseup = null
}
if(isRecover){
// 监听节点的属性变化
// 要观察的目标元素
var targetElement = event.target;
// 创建一个新的 MutationObserver 实例
var observer = new MutationObserver(function(mutationsList, observer) {
// 遍历所有变化的mutation
for (var mutation of mutationsList) {
// 检查是否是属性变化
if (mutation.type === 'attributes' && mutation.attributeName === 'style') {
// 获取目标元素的display属性值
var displayValue = targetElement.style.display;
// 处理display属性变化
if(displayValue === 'none'){
// 停止观察
observer.disconnect();
targetElement.style.right = preRight;
targetElement.style.bottom = preBottom;
}
}
}
});
// 配置MutationObserver监听属性变化
var config = { attributes: true };
// 开始观察目标元素的属性变化
observer.observe(targetElement, config);
}
}
// 鼠标在设置组件按下调用拖拽方法
document.documentElement.addEventListener('mousedown',function (event){
if(event.target.className === 'settingOfFooter')
{
dragFun(event,true,event.target.style.right,event.target.style.bottom)
}
})
js实现拖拽节点到任意位置
于 2023-12-26 17:35:55 首次发布