js实现拖拽节点到任意位置

// 新增拖拽的方法
	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)
		}
	})

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值